我具有基于密钥的数组:
const selected = {
1: [a, b, c],
2: [d, e, f]
}
我需要在第二层上循环循环,并打印其父。因此,我需要我的输出像:
1a
1b
1c
2d
2e
3f
我还没有太远。以下记录整个对象,但我希望它可以在" 1"one_answers" 2"
上运行Array.of(selected).forEach((item)=>{
console.log(item)
});
我很乐意将ES6用于解决方案。
您所需要的只是带有.forEach()
和嵌套环的Object.entries
。
const selected = {
1: ['a', 'b', 'c'],
2: ['d', 'e', 'f']
};
Object.entries(selected)
.forEach(([key, arr]) => arr.forEach(v => console.log(key + v)));
如果您有.length
,则Array.from
将起作用,而不是Array.of
,尽管您的数组稀疏。
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)));
Object.entries()
很棒:
const selected = {
1: ['a', 'b', 'c'],
2: ['d', 'e', 'f']
};
Object.entries(selected).forEach(([key, value]) => {
value.forEach(v => console.log(key + v));
});