简体   繁体   中英

Javascript array de-structuring and Object.entries

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?

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM