非常简单:Object.entries
is supposed to produce and Array
of key, value pairs.。因此,我希望这段代码能够解构
[{
id: 1,
name: "christian"
},{
id : 2,
name: "bongiorno"
}].map(Object.entries).forEach(([k,v]) => console.log(`${k}: ${v}`));
生产:
id:1 name:christian
id:2 name:bongiorno
但它没有。我得到了,而不是:
id,1: name,christian
id,2: name,bongiorno
我错过了什么?
答案 0 :(得分:3)
输出正确,但你的定义略有偏差,你错过了一个数组级别(数组数组)。
Object.entries
应该生成一组键值对的数组。
console.log(
Object.entries({
id: 1,
name: 'test'
})
)

要实现您的目标,您只需将日志更新为嵌套数组的帐户:
[{
id: 1,
name: "christian"
},{
id : 2,
name: "bongiorno"
}]
.map(Object.entries)
.forEach(([k, v]) => console.log(
`${k.join(':')} ${v.join(':')}`
));

或许你想要压扁每个阵列?:
[{
id: 1,
name: "christian"
},{
id : 2,
name: "bongiorno"
}]
.map(Object.entries)
.reduce((arr, curr) => arr.concat(curr), [])
.forEach(([k,v]) => console.log(`${k}: ${v}`));

答案 1 :(得分:2)
让我们尝试删除map
和forEach
,看看你对每个对象做了什么:
let [k, v] = Object.entries({
id: 1,
name: "christian"
});
console.log(`${k}: ${v}`);
let [k, v] = Object.entries({
id : 2,
name: "bongiorno"
});
console.log(`${k}: ${v}`);
现在,如果我们展开Object.entries
来电,则会变为
let [k, v] = [
["id", 1],
["name", "christian"]
];
console.log(`${k}: ${v}`);
let [k, v] = [
["id", 2],
["name", "bongiorno"]
];
console.log(`${k}: ${v}`);
非常准确地反映了您所看到的内容 - k
和v
正在获得指定的数组。
您需要嵌套两个循环:
const arr = [{
id: 1,
name: "christian"
}, {
id: 2,
name: "bongiorno"
}];
for (const obj of arr)
for (const [k, v] of Object.entries(obj))
console.log(k+": "+v);