Loading...

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%",
]
- - Source

Answers

answered 1 week ago jo_va #1

JavaScript does not have associative arrays. 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:

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

answered 1 week ago Nina Scholz #2

You could assign all objects to a single object by taking Object.assign.

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

answered 1 week ago Nick Parsons #3

You can use .reduce and the spread syntax to put each object in your values array into the new accumulated object like so:

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

valObj = values.reduce((acc, obj) => ({...acc, ...obj}), {});
console.log(valObj);

answered 1 week ago Khyati Sharma #4

In javascript, you can use Object.assign to store the object in key/value pair because JavaScript does not Support associative arrays. 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);

comments powered by Disqus