简体   繁体   中英

Loop through object's keys, then loop through values (because they are arrays)

I have this object:

 const example = { first: [*arrays objects*], second: [*arrays objects*], third: [*arrays objects*] } 

So, the situation is this: the example has 3 keys. Each key has an array of objects. First i want to loop through the objects keys (first, second, third), then the array of them (with forEach). How can i do that?

Object.keys( object ) will give you the keys of an object as an array.

const example = ...
Object.keys( example ).forEach( ( key, index ) => {
    example[key]; // This is your array you wish to loop through.
});

To loop an object you need to specify what are you looping, in this case i use the keys

 Object.keys(example).forEach()

Hope this helps :>

 const example = { first: [{object: '1'},{object: '2'}], second: [{object: '3'},{object: '4'}] } Object.keys(example).forEach( entrie => { console.log(entrie) example[entrie].forEach(object => { console.log(object) }) }) 

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