有一个数组:
var array = [{test: 1}, {test: 2}, {test: 3}]
我需要得到:
{1: 'random_value', 2: 'random_value', 3: 'random_value'}
我在做:
var values_test = _.map(array, 'test');
下一步做什么?
答案 0 :(得分:1)
您可以使用reduce()
来获得所需的结果。
var array = [{test: 1}, {test: 2}, {test: 3}];
var result = array.reduce(function(r, o) {
r[o.test] = 'random_value';
return r;
}, {})
console.log(result)

使用Lodash
var array = [{test: 1}, {test: 2}, {test: 3}];
var result = _.reduce(array, function(r, o) {
r[o.test] = 'random_value';
return r;
}, {})
console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
&#13;
答案 1 :(得分:0)
您可以尝试这样的事情:
var array = [{
test: 1
}, {
test: 2
}, {
test: 3
}]
var r = _.map(array, x => {
let o = {}
o[x.test] = 'random value'
return o
});
console.log(r)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>