I have key based arrays:
const selected = {
1: [a, b, c],
2: [d, e, f]
}
I need to loop over each item in the second level and also print its parent. So I need my output to be something like:
1a
1b
1c
2d
2e
3f
I havn't got very far. The following loggs the whole object but I expected it to run on '1' and '2'
Array.of(selected).forEach((item)=>{
console.log(item)
});
Im using babel so happy to use ES6 for the solution.
Object.entries()
is great:
const selected = { 1: ['a', 'b', 'c'], 2: ['d', 'e', 'f'] }; Object.entries(selected).forEach(([key, value]) => { value.forEach(v => console.log(key + v)); });
All you need is Object.entries
with .forEach()
and a nested loop.
const selected = { 1: ['a', 'b', 'c'], 2: ['d', 'e', 'f'] }; Object.entries(selected) .forEach(([key, arr]) => arr.forEach(v => console.log(key + v)));
The Array.from
would work instead of Array.of
if you had a .length
, though you'd have a sparse array.
const selected = { 1: ['a', 'b', 'c'], 2: ['d', 'e', 'f'], length: 3, }; Array.from(selected) .forEach((arr, i) => arr && arr.forEach(v => console.log(i + v)));
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.