简体   繁体   中英

Javascript: How to differentiate object literals

I want to know how we can differentiate between object literals and json objects, with other objects such as Date, Function, etc.

Since the typeof operator as well as the instanceof Object operator returns true for both of the object, is there a way to differentiate between them?

PS: I don't want to do it by reverse exclusion of Date and Function, since it won't handle cases other than Date or function.

Everything non-primitive is an object, but not everything that's an object is also a Date, or a function. Instead of checking instanceof Object , check instanceof Date , or instanceof Function :

 const obj = {}; const date = new Date(); const fn = () => 'foo'; console.log(date instanceof Date); console.log(obj instanceof Date); console.log(fn instanceof Function); console.log(obj instanceof Function); 

and json objects

Keep in mind that there's no such thing as a "JSON Object"

If you just want to make a copy of a Javascript object (including arrays, since they're objects too), but excluding non-valid JSON objects (like Date s, Function s, etc.), one of the simplest way is to convert the Javascript object to JSON string, and then re-parse it:

function deepCopy(input){
  const json = JSON.stringify(input);
  return JSON.parse(json);
}

const obj1 = { "hello": "world" };
const obj2 = deepCopy(obj1);

// obj1 and obj2 are two distinct objects
obj1["hello"] = "bye";
console.log( obj2["hello"] ); // world

// this works for arrays too
const a = [1, 2, [3, 4]];
const b = deepCopy(a);

NOTE: be aware that, even if it works, it is not the best solution (especially because of performance issues).

You can also write a function, whose purpose is to analyze a Javascript object in order to see if it can be a valid JSON object (ie a plain Object with only primitives and arrays in it). This way, you can differentiate from Date s and other "complex" objects. Take a look at JSON specification (or Wikipedia) in order to know which data types JSON supports.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM