Javascript:在给定现有对象的情况下使用循环设置对象键
Javascript: Setting object keys with loop given existing object
我的 objective 是创建一个函数,其中 returns 一个新对象,由作为名称的键和作为玩家编号的值组成:
var newObj = {"Brandon Bass": 2, "Tarik Black":19,...}
我有这个对象:
var playerObj = {
players: [{
name: "Brandon Bass",
number: 2,
stats: {
points: 2.5
}
},
{
name: "Tarik Black",
number: 19,
stats: {
points: 2.5
}
}, {
name: "Anothy Broqn",
number: 11,
stats: {
points: 4.8
}
},
{
name: "Kobe Bryant",
number: 22,
stats: {
points: 5.6
}
}
]};
这是my most recent attempt。这可能吗?
for (var key in playerObj.players) {
var newObj = {};
for (var i = 0; i < playerOjb.players.length; i++) {
newObj[playerObj.players[i]] = playerObj.players[key].number;
}
return newObj;
}
当循环数组时,使用标准的 for
循环,而不是 for..in
,然后简单地创建对象:
var newObj = {}
for (var i = 0; i < playerObj.players.length; i++) {
newObj[playerObj.players[i].name] = playerObj.players[i].number;
}
尝试 reduce
这样的数组,
var newObj = playerObj.players.reduce(function(old,itm){
old[itm.name] = itm.number
return old;
}, {});
DEMO
我的 objective 是创建一个函数,其中 returns 一个新对象,由作为名称的键和作为玩家编号的值组成:
var newObj = {"Brandon Bass": 2, "Tarik Black":19,...}
我有这个对象:
var playerObj = {
players: [{
name: "Brandon Bass",
number: 2,
stats: {
points: 2.5
}
},
{
name: "Tarik Black",
number: 19,
stats: {
points: 2.5
}
}, {
name: "Anothy Broqn",
number: 11,
stats: {
points: 4.8
}
},
{
name: "Kobe Bryant",
number: 22,
stats: {
points: 5.6
}
}
]};
这是my most recent attempt。这可能吗?
for (var key in playerObj.players) {
var newObj = {};
for (var i = 0; i < playerOjb.players.length; i++) {
newObj[playerObj.players[i]] = playerObj.players[key].number;
}
return newObj;
}
当循环数组时,使用标准的 for
循环,而不是 for..in
,然后简单地创建对象:
var newObj = {}
for (var i = 0; i < playerObj.players.length; i++) {
newObj[playerObj.players[i].name] = playerObj.players[i].number;
}
尝试 reduce
这样的数组,
var newObj = playerObj.players.reduce(function(old,itm){
old[itm.name] = itm.number
return old;
}, {});