如何为对象中的所有键和值添加属性?

时间:2018-09-18 06:52:57

标签: javascript arrays map-function

我有一个Javascript对象:

{
    "Central":73322346.47533998,
    "East":87801368.39711998,
    "North":76468694.37534,
    "South":142687496.66816995,
    "West":76815749.40554999
}

我想将此对象映射到一个看起来像这样的数组

[
    {"name" :"Central ,"size" : 73322346.47533998},
    {"name" : "East", "size" : 87801368.39711998},
    {"name": "North","size":76468694.37534},
    {"name": "South","size" :142687496.66816995},
    {"name":"West","size":76815749.40554999}
]

我该怎么办?

4 个答案:

答案 0 :(得分:3)

这样做:

obj = {"Central":73322346.47533998,"East":87801368.39711998,"North":76468694.37534,"South":142687496.66816995,"West":76815749.40554999}
out = [];
Object.keys(obj).forEach(function(d){ out.push({name: d, size: obj[d]});})
//out will contain your formatted data

enter image description here

答案 1 :(得分:2)

在ES2017中,您可以执行以下操作:

Object.entries(obj).map(([name, size])=> ({name, size}))

var obj = {
    "Central":73322346.47533998,
    "East":87801368.39711998,
    "North":76468694.37534,
    "South":142687496.66816995,
    "West":76815749.40554999
}

var res = Object.entries(obj).map(([name, size])=> ({name, size}));

console.log(res);

在ES2011(5.1),ES2015(6),....及更高版本中,您可以执行以下操作:

Object.keys(obj).map(function(k) {
    return {name: k, size: obj[k]}
})

var obj = {
    "Central":73322346.47533998,
    "East":87801368.39711998,
    "North":76468694.37534,
    "South":142687496.66816995,
    "West":76815749.40554999
}

var res = Object.keys(obj).map(function(k) {
    return {name: k, size: obj[k]}
})

console.log(res)

答案 2 :(得分:1)

您可以遍历对象的key来获得预期的对象数组:

var data = {"Central":73322346.47533998,"East":87801368.39711998,"North":76468694.37534,"South":142687496.66816995,"West":76815749.40554999};
var res = [];
Object.keys(data).forEach((key)=>{
  res.push({
    name: key,
    size: data[key]
  });
});
console.log(res);

答案 3 :(得分:0)

一种简单的方法是使用for..in loop插入输入对象的键:

const input = {
    "Central": 73322346.47533998,
    "East": 87801368.39711998,
    "North": 76468694.37534,
    "South": 142687496.66816995,
    "West": 76815749.40554999
};

let output = [];
for (const key in input)
{
    output.push({ "name": key, "size": input[key] });
}

console.log(output);

这可能是获得所需输出的最快方法。