Javascript数组解构和Object.entries

时间:2017-07-11 05:37:01

标签: javascript ecmascript-6 destructuring

非常简单: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

我错过了什么?

2 个答案:

答案 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)

让我们尝试删除mapforEach,看看你对每个对象做了什么:

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}`);

非常准确地反映了您所看到的内容 - kv正在获得指定的数组。

您需要嵌套两个循环:

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);