Javascript: Convert list of values to set of Objects

Viewed 78

I am fetching data from server..

Data returned from server is..

{
 Increase: true,
Decrease: false,
Like:true,
Unlike: true,
Others: false,
Limits:true
}

Below is what i get after Ngrx service dispatch

console.log('this.data=' +data);

this.data= [object Object]

Now after doing console.log('Object.keys(data)='+ Object.keys(data));

Object.keys(data)= Increase,Decrease,Like,Unlike,Others,Limits

How can i get same set of data like below after console.log

  [object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

so that after JSON.stringify.. i can get that same data like below

[{"description":"Increase"},{"description":"Decrease"},{"description":"Like"},{"description":"Unlike"},{"description":"Others"},{"description":"Limits"},]
2 Answers

You can take entries and then map it:

var obj={ Increase: true, Decrease: false, Like:true, Unlike: true, Others: false, Limits:true};

var result = Object.entries(obj).map(([k,v])=>({[k]:v}));

var result2 = Object.entries(obj).map(([k])=>({'Description':k}));

console.log(result);
console.log(result2);

You can use Object.keys() then .map() the result array, this is a working snippet:

const obj = {
  Increase: true,
  Decrease: false,
  Like: true,
  Unlike: true,
  Others: false,
  Limits: true,
};

//const result = Object.keys(obj).map((key) => ({ description: key }));

const result = Object.keys(obj).map((key) => ({ [key]: obj[key]}));

console.log(JSON.stringify(result));

Related