简体   繁体   English

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

[英]How to add properties for all the keys and values in an object?

I have a Javascript Object : 我有一个Javascript对象:

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

I want to map this object into an array that look like this 我想将此对象映射到如下所示的数组中

[
    {"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}
]

How do I go about? 我该怎么办?

do like this: 这样做:

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

在此处输入图片说明

In ES2017 you can do: 在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); 

In ES2011 (5.1), ES2015 (6),.... and onward you can do: 在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) 

You can loop over the key s of the object to get the array of objects as expected: 您可以遍历对象的key s,以获取期望的对象数组:

 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); 

A simple way to do this is to interate over the keys of the input object using a for..in loop : 一种简单的方法是使用for..in循环遍历输入对象的键:

 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); 

This is probably the fastest way to achieve the desired output. 这可能是获得所需输出的最快方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM