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?
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.
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.
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With