Javascript array de-structuring and Object.entries

半腔热情 提交于 2019-12-24 02:15:45

问题


It's pretty simple: Object.entries is supposed to produce and Array of key, value pairs.. As such, I would expected this code to destructure

[{
  id: 1,
  name: "christian"
},{
  id : 2,
  name: "bongiorno"
}].map(Object.entries).forEach(([k,v]) => console.log(`${k}: ${v}`));

into producing:

id:1 name:christian
id:2 name:bongiorno

But it doesn't. I get, instead:

id,1: name,christian
id,2: name,bongiorno

What did I miss?


回答1:


The output is correct but your definition is slightly off, you're missing an array level (array of arrays).

Object.entries is supposed to produce an array of arrays of key, value pairs.

console.log(
  Object.entries({
    id: 1,
    name: 'test'
  })
)

To achieve what you want, you can just update your log to account for nested arrays:

[{
  id: 1,
  name: "christian"
},{
  id : 2,
  name: "bongiorno"
}]
  .map(Object.entries)
  .forEach(([k, v]) => console.log(
    `${k.join(':')} ${v.join(':')}`
  ));

Or maybe you meant to flatten each array?:

[{
  id: 1,
  name: "christian"
},{
  id : 2,
  name: "bongiorno"
}]
  .map(Object.entries)
  .reduce((arr, curr) => arr.concat(curr), [])
  .forEach(([k,v]) => console.log(`${k}: ${v}`));
  



回答2:


Let's try to drop the map and forEach and see what you did with each of the objects:

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

Now if we expand the Object.entries call, this becomes

let [k, v] = [
  ["id", 1],
  ["name", "christian"]
];
console.log(`${k}: ${v}`);

let [k, v] = [
  ["id", 2],
  ["name", "bongiorno"]
];
console.log(`${k}: ${v}`);

which quite accurately reflects what you're seeing - k and v are getting assigned arrays.

You will need to nest two loops:

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


来源:https://stackoverflow.com/questions/45026162/javascript-array-de-structuring-and-object-entries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!