Simple way to flatten this array?

I have this array:

[{name: 'email',value: 'a@b.com'}, {name: 'phone',value: '123-123-1234'}]

I need to turn it into this:

{email: 'a@b.com', phone: '123-123-1234'}

How can I do this? I figure I can do a million iterators to get the job done, but I think maybe there's a cleaner way to do this.

I'm using Underscore and jQuery if that helps.


There are several ways to do that task.

One is using Array.prototype.map :

var arr = [{name: 'email',value: 'a@b.com'}, {name: 'phone',value: '123-123-1234'}];
var obj = {};
arr.map(function (item) {
   var key = item.name;
   var value = item.value;
   if (!obj[key]) {
      obj[key] = value;
   }
});
console.log(obj);

As noted in the comments and other answer, .reduce() , .forEach() or a simple for-loop can get the job done as well.


Array.prototype.reduce对于这种类型的操作非常简单:

var items = [{name: 'email',value: 'a@b.com'}, {name: 'phone',value: '123-123-1234'}]

var data = items.reduce(function (result, item) {
    result[item.name] = item.value;

    return result;
}, {});

UnderscoreJS is just awesome, and you may use _.map . See the code below:

var existingObject = [{name: 'email',value: 'a@b.com'}, {name: 'phone',value: '123-123-1234'}];
var selectedObject = _.map(existingObject, function(obj) {
    var retObj = { };
    retObj[obj["name"]] = obj["value"];
    return retObj;
});

console.log(selectedObject);
链接地址: http://www.djcxy.com/p/70632.html

上一篇: 从外部触发FullCalendar的'dayClick'方法?

下一篇: 简单的方法来压扁这个数组?