Javascript:在给定现有对象

时间:2016-02-25 20:08:54

标签: javascript oop object for-loop key-value

我的目标是创建一个函数,该函数返回一个新的对象,该对象由作为名称和值的键组成,作为玩家编号:

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

2 个答案:

答案 0 :(得分:2)

循环数组时,使用标准for循环,而不是for..in,然后只需按原样创建对象:

var newObj = {}
for (var i = 0; i < playerObj.players.length; i++) {
    newObj[playerObj.players[i].name] = playerObj.players[i].number;
}

答案 1 :(得分:1)

尝试reduce这样的数组,

secure

DEMO