简体   繁体   中英

Change the structure of an object in JS

const a = {
  0: { country: "france", date:"sfzef"},
  1: { country: "italie", date:"ttttt"},
  2: { country: "belgique", date:"zzzee"}
}

let obj = {}
for (const property in a) {
  obj = {...obj, `${a[property].country}: ${a[property]}`}
}

I would like to have :

obj = {
  france: { country: "france", date:"sfzef"},
  italie: { country: "italie", date:"ttttt"},
  belgique: { country: "belgique", date:"zzzee"}
}

I've been trying for 4 hours, thanks in advance to the one who will help me

You're close, but you're creating a string, when you need to be doing a key/value pair of the object. A computed key can be done with square brackets around the key:

 const a = { 0: { country: "france", date:"sfzef"}, 1: { country: "italie", date:"ttttt"}, 2: { country: "belgique", date:"zzzee"} } let obj = {} for (const property in a) { obj = {...obj, [a[property].country]: a[property]} } console.log(obj);

If you want to avoid copying the object each time, you can do this:

let obj = {}
for (const property in a) {
  obj[a[property].country] = a[property]
}

Alternative: use a reducer on the entries of the Object (see MDN )

 const a = { 0: { country: "france", date:"sfzef"}, 1: { country: "italie", date:"ttttt"}, 2: { country: "belgique", date:"zzzee"} }; const b = Object.entries(a) .reduce( (acc, [key, value]) => ({...acc, [value.country]: value}), {} ); console.log(b);

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