使用Underscorejs对象的数组

时间:2016-08-18 15:15:19

标签: underscore.js

我有一个包含多个对象的数组,

[{Reinvent:24},{Reorganize:18},{Reduce:36},{Reimagine:30}]

我正在寻找以下格式的输出,仅使用underscorejs,

{Reinvent:24,Reorganize:18,Reduce:36,Reimagine:30}

2 个答案:

答案 0 :(得分:2)

这应该做你想要的:

angular.module('myApp').controller(function($stateParams){
  if($stateParams.url == null){
    //do something ; pretend you are in page-0
  }else{
   //do something ; pretend you are in page-1
  }
});

您可以将任意数量的源参数传递给下划线的extend函数。为了利用这一点,我们可以使用Javascript的apply函数将参数作为数组提供。

或者你可以使用ES6的spread operator

var result = _.extend.apply({}, data);

var result = _.extend({}, ...data);
var data = [{Reinvent:24},{Reorganize:18},{Reduce:36},{Reimagine:30}];

var result = _.extend.apply({}, data);   

document.getElementById('result').textContent = JSON.stringify(result);

答案 1 :(得分:1)

您可以使用_.reduce

var res = _.reduce(arr, function(acc, el) {
  for (var key in el) {
    acc[key] = el[key];
  }
  return acc;
}, {});



var arr = [{Reinvent:24},{Reorganize:18},{Reduce:36},{Reimagine:30}];

var res = _.reduce(arr, function(acc, el) {
  for (var key in el) {
    acc[key] = el[key];
  }
  return acc;
}, {});

console.log(res);

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
&#13;
&#13;
&#13;