Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting object properties to array of objects

I'm getting output that looks like this:

{'1536135941922': 'true',
 '1536135962942': 'false',
 '1536135986966': 'false',
 '1536135989968': 'true'}

and I need it to look like this:

[{'1536135941922': 'true'},
 {'1536135962942': 'false'},
 {'1536135986966': 'false'},
 {'1536135989968': 'true'}]

So my front can consume it. What is the way that I can convert it?

like image 296
Neven Jovic Avatar asked Sep 05 '18 09:09

Neven Jovic


People also ask

How do you turn an object into an array?

To convert an object to an array you use one of three methods: Object.keys() , Object.values() , and Object.entries() . Note that the Object.keys() method has been available since ECMAScript 2015 or ES6, and the Object.values() and Object.entries() have been available since ECMAScript 2017.

Can an object property be an array?

Just as object properties can store values of any primitive data type (as well as an array or another object), so too can arrays consist of strings, numbers, booleans, objects, or even other arrays.

How do you change the properties of an array of objects?

To update an object's property in an array of objects, use the map() method to iterate over the array. On each iteration, check if the current object is the one to be updated. If it is, modify the object and return the result, otherwise return the object as is.

What method should we use to turn an object containing other objects into an array?

When converting an object to an array, we'll use the . entries() method from the Object class. This will convert our object to an array of arrays. Each nested array is a two-value list where the first item is the key and the second item is the value.


1 Answers

You can use Object.entries() and .map() methods to get the desired output:

let data = {
  '1536135941922': 'true',
  '1536135962942': 'false',
  '1536135986966': 'false',
  '1536135989968': 'true'
};
  
let result = Object.entries(data).map(( [k, v] ) => ({ [k]: v }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 62
Mohammad Usman Avatar answered Oct 11 '22 06:10

Mohammad Usman