简体   繁体   中英

How to check if the key exist in json array?

I have a json object, the structure of which is given below. I try to find if the key (for eg: 1 & 2 ) exist or not by myArray.includes( '1' ) but it doesn't work. Is looping through the array the only way to check if attribute exist or not?

[{"1": [{}]},{"2": [{}]}]

您必须遍历 Array 中的所有元素,并检查每个对象中是否存在键。

arr.some(e => e.hasOwnProperty('1'));

The way to check if an object with a particular property exists or not would be to filter the objects by verifying if they have given property or not.

To check if an object contains a property you could use Array.prototype.includes on the list of keys obtained through Object.keys . Here's an example:

 var data = [ {"1" : []}, {"2" : []} ]; // Count of objects containing a given key. console.log(data.filter(t => Object.keys(t).includes("1")).length); console.log(data.filter(t => Object.keys(t).includes("2")).length); console.log(data.filter(t => Object.keys(t).includes("3")).length);

You can use use some() and Object.prototype.hasOwnProperty()

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

 let arr = [{ "1":[{}], "2":[{}] }] let checkOne = arr.some(x => x.hasOwnProperty('1')); let checkThree = arr.some(x => x.hasOwnProperty('3')); console.log(checkOne) //true console.log(checkThree) //false

You can use Array.some() which tests whether at least one element in the array passes the test.

const has1 = myArray.some(obj => obj.hasOwnProperty(“1”)); // Returns a boolean
const has2 = myArray.some(obj => obj.hasOwnProperty(“2”)); // Returns a boolean

You can try forEach to loop the keys of object and check if yours is there.

var obj = yourobject;

var mykey = 0;

Object.keys(obj).forEach(function(k){
    if(k == mykey){
    ...
}

});

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