Neven Jovic
Neven Jovic

Reputation: 197

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?

Upvotes: 16

Views: 26854

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386868

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

Upvotes: 5

Mohammad Usman
Mohammad Usman

Reputation: 39392

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

Upvotes: 26

FK82
FK82

Reputation: 5075

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.

Upvotes: 3

Daniele Tentoni
Daniele Tentoni

Reputation: 310

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.

Upvotes: 0

Related Questions