问题
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?
回答1:
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; }
回答2:
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.
回答3:
You could map the entries of the object by using new objects.
Methods:
Object.entries
Array#map
arrow functions
destructuring assignment
computed property names
var object = { '1536135941922': 'true', '1536135962942': 'false', '1536135986966': 'false', '1536135989968': 'true' },
array = Object.entries(object).map(([k, v]) => ({ [k]: v }));
console.log(array);
回答4:
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.
来源:https://stackoverflow.com/questions/52181220/converting-object-properties-to-array-of-objects