I need to determine if a certain key exists in an array of objects.
Here is a sample array:
arrOfObj = [{
"mainKey1": {
"subKey1": {
"innerKey1": {
"innerMostKey1": {
"key1": "value"
}
}
}
}
}, {
"mainKey2": {
"key2": "value"
}
}, {
"mainKey3": {
"subKey3": {
"key3": "value"
}
}
}
]
I was trying to do this but I get the wrong output:
const objKeys = Object.keys(arrOfObj)
console.log('objKeys = ' + JSON.stringify(arrOfObj))
Output is the index numbers:
objKeys = ["0", "1", "2"]
I want to have a function that works like this:
var isKeyPresent = checkKeyPresenceInArray('mainKey3')
Please note though that I only need to check the topmost level in the objects - in above example, these are the main keys (mainKey1
, etc) and that their content is dynamic (some others have deeply nested object inside and some not so.
Help!
Using the Object. key generates and returns an array whose components are strings of the names (keys) of an object's properties. This may be used to loop through the object's keys, which we can then use to verify if any match a certain key in the object.
Use the in operator to check if a key exists in an object, e.g. "key" in myObject . The in operator will return true if the key is present in the object, otherwise false is returned. Copied! The syntax used with the in operator is: string in object .
JavaScript objects don't have a filter() method, you must first turn the object into an array to use array's filter() method. You can use the Object. keys() function to convert the object's keys into an array, and accumulate the filtered keys into a new object using the reduce() function as shown below.
You can try using array.some()
:
let checkKeyPresenceInArray = key => arrOfObj.some(obj => Object.keys(obj).includes(key));
let arrOfObj = [{
"mainKey1": {
"subKey1": {
"innerKey1": {
"innerMostKey1": {
"key1": "value"
}
}
}
}
}, {
"mainKey2": {
"key2": "value"
}
}, {
"mainKey3": {
"subKey3": {
"key3": "value"
}
}
}
]
let checkKeyPresenceInArray = key => arrOfObj.some(obj => Object.keys(obj).includes(key));
var isKeyPresent = checkKeyPresenceInArray('mainKey3')
console.log(isKeyPresent);
You can iterate through the array, check and see if any of the objects has the key that you are looking for, and return true if it does. If you don't find the key, then the for
loop will complete and it will return false.
arrOfObj = [{
"mainKey1": {
"subKey1": {
"innerKey1": {
"innerMostKey1": {
"key1": "value"
}
}
}
}
}, {
"mainKey2": {
"key2": "value"
}
}, {
"mainKey3": {
"subKey3": {
"key3": "value"
}
}
}
]
function arrayHasKey(arr, key) {
for (const obj of arr) {
if (key in obj) { return true; }
}
return false;
}
console.log(arrayHasKey(arrOfObj, "mainKey2"))
console.log(arrayHasKey(arrOfObj, "mainKey10"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With