I have a JSON object( mainObj
) which in turn has objects (say obj1
, obj2
, obj3
). What I am trying to achieve is when I check for a condition iterating through every obj in the mainObj
and if it holds true, I want to add only the name of that obj
in an array of String. Something like,
for(obj in mainObj){
if(obj holds condition){
add the descriptor of the obj (in string format) to an array (not the entire obj)
}
You can use Object.keys()
to iterate over your object keys, then use Array.filter()
to filter the keys, here I am checking if the inner objects have a property show
and if this property is truthy:
const mainObj = { obj1: { show: true, a: 1 }, obj2: { show: false, a: 2 }, obj3: { a: 3 }, obj4: { show: true, b: 1 } }; const result = Object.keys(mainObj).filter(key => mainObj[key].show); console.log(result);
If you want to use a for-in
loop, you have to make sure the property is part of the object and is not inherited from its protype chain using Object.hasOwnProperty()
:
const mainObj = { obj1: { show: true, a: 1 }, obj2: { show: false, a: 2 }, obj3: { a: 3 }, obj4: { show: true, b: 1 } }; const result = []; for (const prop in mainObj) { if (mainObj.hasOwnProperty(prop) && mainObj[prop].show) { result.push(prop); } } console.log(result);
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.