[英]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我已经尝试了 4 个小时,提前感谢帮助我的人
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 )替代方法:在
Object
的条目上使用reducer
(参见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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.