Javascript:数组中的对象,包含id的对象

时间:2014-10-21 11:21:50

标签: javascript arrays object lodash

我有一个这样的数组:

[
  {id: 32, color: 'ff00dd'},
  {id: 64, color: 'ab230b'},
  {id: 102, color: '5f561d'}
]

如何将其转换为以下格式:

{ 32: 'ff00dd', 64: 'ab230b', 102: '5f561d'}

LoDash可用)

提前致谢!

3 个答案:

答案 0 :(得分:3)

如果没有LoDash,一个简单的for循环可以为我们做到这一点:

var data = [
    {id: 32, color: 'ff00dd'},
    {id: 64, color: 'ab230b'},
    {id: 102, color: '5f561d'}
  ],
  obj = {};

for (var i = 0; i < data.length; i++)
    obj[data[i].id] = data[i].color;

console.log(obj);
Open your JavaScript console to see the result.

以上代码段中记录的控制台输出为:

> Object {32: "ff00dd", 64: "ab230b", 102: "5f561d"} 

答案 1 :(得分:2)

使用lodash:

_.zipObject(_.pluck(a, 'id'), _.pluck(a, 'color'));

答案 2 :(得分:1)

您可以循环遍历数组中的对象,然后将每个对象作为属性添加到新对象上:

var data = [
  {id: 32, color: 'ff00dd'},
  {id: 64, color: 'ab230b'},
  {id: 102, color: '5f561d'}
];
var newObject = {};

_(data).forEach(function(obj) {
    newObject[obj.id] = obj.color;
});