下划线从对象元素创建对象数组

时间:2013-10-09 12:57:17

标签: javascript underscore.js

您好我有这样的对象:

var obj = { banana: 1425, orange: 1683}

我需要基于项目创建的对象数组。 例如:

[{name: banana, value: 1425}, {name: orange, value: 1683}]

我是这样做的:

var fruits = [];
_.each(obj, function(value, name){
    fruits.push({
        name: name,
        value: value
    });
});

也许你知道一种更简单的方法吗?

2 个答案:

答案 0 :(得分:10)

您可以在对象上使用下划线的_.map:

var obj = { banana: 1425, orange: 1683};

var fruits = _.map(obj, function(value, key){
  return { name : key, value : value };
});

http://underscorejs.org/#map

答案 1 :(得分:0)

You could also just use Object.entries()

let myobj = {banana: 1425, orange: 1683};
let entries = Object.entries(myobj); // => [['banana', 1425], ['orange', 1683]];


//and if you want it in array-object format:
let other_format = Object.entries(myobj).map(entry => {
    return {[entry[0]]: entry[1]}
}); // => [{banana: 1425}, {orange: 1683}]