Home > database >  Converting object values and properties into an array
Converting object values and properties into an array

Time:04-04

How to convert an object with names and values into an array of object just like the below format.

  'result' : { "name1" : "Angle", "name2" : "Demon", "name3" : "Hunter"}

Desired output :

  "result" : [
                 {'name1' : 'Angle'},
                 {'name2' : 'Demon'},
                 {'name3' : 'Hunter'}
             ]

CodePudding user response:

You can use Object.entries and Array#map methods as follows:

const input = {'result' : { "name1" : "Angle", "name2" : "Demon", "name3" : "Hunter"}}

const output = [input].map(
    ({result}) => 
    ({result: Object.entries(result).map(([k,v]) => ({[k]:v}))})
)[0];

console.log( output );

CodePudding user response:

const result = { "name1" : "Angle", "name2" : "Demon", "name3" : "Hunter"};

const res = Object.keys(result).map(item => {
  const obj = {};
  obj[item] = result[item]
  return obj;
});

console.log(res);

  • Related