简体   繁体   中英

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?

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

This is a one-liner with Object.entries and Array.map :

 const data = {'1536135941922': 'true', '1536135962942': 'false', '1536135986966': 'false', '1536135989968': 'true'}; const convert = (object) => Object.entries(data).map(([key, value]) => ({ [key]: value })); console.log(convert(data)); 

What is your backend set-up? I was assuming Node since you tagged with javascript .

You could map the entries of the object by using new objects.

Methods:

 var object = { '1536135941922': 'true', '1536135962942': 'false', '1536135986966': 'false', '1536135989968': 'true' }, array = Object.entries(object).map(([k, v]) => ({ [k]: v })); console.log(array); 

If you are using PHP you can create object for object and push them to an array. After that, you can convert the array object to json with json_encode functions and return it to your front.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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