gpt4 book ai didi

javascript - 创建对象时如何在属性中给出数组索引

转载 作者:行者123 更新时间:2023-11-29 16:40:17 29 4
gpt4 key购买 nike

我正在 javascript a 中创建一个基于一些数组数据的对象

var myArr = [
{
"id": 1,
"Music": "POP",
"Singer": "Abc",
"Country": "IND"
},
{
"id": 2,
"Music": "JAZZ",
"Singer": "xyz",
"Country": "USA"
},
{
"id": 3,
"Music": "BLUES",
"Singer": "def",
"Country": "ENG"
}
]

现在基于这个数组,我尝试创建一个具有以下内容的数组对象

id、值和国家/地区。

这是我正在尝试的

var myObj = [];

for (var i = 0; i < myArr.length; i++) {
var obj = {
id: i,
Value: myArr[i].Music,
myArr[i].Singer : myArr[i].Country,
}
myObj.push(obj);
}

但是在此 for 循环期间 myArr[i].Singer 抛出错误。怎么解决这个问题。

最佳答案

对于数组,获取所需的键并直接在对象字面量之外分配值。

var myArr = [{ id: 1, Music: "POP", Singer: "Abc", Country: "IND" }, { id: 2, Music: "JAZZ", Singer: "xyz", Country: "USA" }, { id: 3, Music: "BLUES", Singer: "def", Country: "ENG" }],
myObj = [],
obj;

for (var i = 0; i < myArr.length; i++) {
obj = {
id: i,
Value: myArr[i].Music
}
obj[myArr[i].Singer] = myArr[i].Country;
myObj.push(obj);
}

console.log(myObj);
.as-console-wrapper { max-height: 100% !important; top: 0; }

使用 ES6,您可以使用 computed property names并将该对象映射为新数组。

var array = [{ id: 1, Music: "POP", Singer: "Abc", Country: "IND" }, { id: 2, Music: "JAZZ", Singer: "xyz", Country: "USA" }, { id: 3, Music: "BLUES", Singer: "def", Country: "ENG" }],
result = array.map((o, i) => ({ id: i, Value: o.Music, [o.Singer]: o.Country}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 创建对象时如何在属性中给出数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46910396/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com