简体   繁体   English

将对象数组转换为具有键值的数组

[英]Convert an array of objects into an array with key values

How to convert an array of objects into an array with keys and values. 如何将对象数组转换为具有键和值的数组。 We are sure to each object contain only one value. 我们确保每个对象仅包含一个值。

"values":[
    {
        "first(%)":"91.52%"
    },
    {
        "second(%)":"98.98%"
    },
    {
        "Total(%)":"95.00%"
    }
]

Desired output: 所需的输出:

"values":[
    "first(%)":"91.52%",
    "second(%)":"98.98%",
    "Total(%)":"95.00%",
]

You could assign all objects to a single object by taking Object.assign . 您可以通过采用Object.assign将所有对象分配给单个对象。

 var object = { values: [{ "first(%)": "91.52%" }, { "second(%)": "98.98%" }, { "Total(%)": "95.00%" }] }, result = { values: Object.assign({}, ...object.values) }; console.log(result); 

You can use .reduce and the spread syntax to put each object in your values array into the new accumulated object like so: 您可以使用.reducespread语法将值数组中的每个对象放入新的累积对象中,如下所示:

 const values=[{"first(%)":"91.52%"},{"second(%)":"98.98%"},{"Total(%)":"95.00%"}], valObj = values.reduce((acc, obj) => ({...acc, ...obj}), {}); console.log(valObj); 

JavaScript does not have associative arrays. JavaScript没有关联数组。 However you can use objects to store key/values. 但是,您可以使用对象存储键/值。

Here is a way to extract the key/values from the items in the array and set them on an object using reduce : 这是一种从数组中的项中提取键/值并使用reduce对其设置的方法:

 const data = { "values": [ { "first(%)":"91.52%"}, { "second(%)":"98.98%" }, { "Total(%)":"95.00%" } ] }; const result = data.values.reduce((acc, x) => { Object.entries(x).forEach(([key, val]) => acc[key] = val); return acc; }, {}); console.log(result); 

In javascript, you can use Object.assign to store the object in key/value pair because JavaScript does not Support associative arrays. 在JavaScript中,您可以使用Object.assign将对象存储在键/值对中,因为JavaScript不支持关联数组。 You can use it as an object. 您可以将其用作对象。

 const data = { values: 
              [{ "first(%)": "91.52%" },
               { "second(%)": "98.98%" },
               { "Total(%)": "95.00%" }] };

 const result = { values: Object.assign({}, ...data.values) };

console.log("result",result);

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

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