Converting object properties to array of objects

Viewed 14356

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?

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

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

With Object.fromEntries:

var object = { '1536135941922': 'true', '1536135962942': 'false', '1536135986966': 'false', '1536135989968': 'true' },
    array = Object
        .entries(object)
        .map(pair => Object.fromEntries([pair]));
  
console.log(array);
.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.

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.

Related