Nandakumar singh
Nandakumar singh

Reputation: 47

Converting object values and properties into an array

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'}
             ]

Upvotes: 0

Views: 277

Answers (4)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Using Object.fromEntries and Object.entries

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

const result = Object.entries(input).map((ent) => Object.fromEntries([ent]));

console.log(result);

Upvotes: 0

Wyck
Wyck

Reputation: 11720

Using Object.entries:

const input = { "name1": "Angle", "name2": "Demon", "name3": "Hunter" };
const result = Object.entries(input).map(([k, v]) => ({ [k]: v }));
console.log(result);

Using Object.keys:

const input = { "name1": "Angle", "name2": "Demon", "name3": "Hunter" };
const result = Object.keys(input).map(k => ({ [k]: input[k] }));
console.log(result);

A breakdown of the syntactic gymnastics of the arrow function given to map.

Notice where we have:

.map(([k, v]) => ({ [k]: v })

Basically, each element of the array returned by Object.entries is itself an array with two values, the first is the property name (key) and the second is the property value. For this example, Object.entries(input) returns:

[
  [ "name1", "Angle" ],
  [ "name2", "Demon" ],
  [ "name3", "Hunter" ]
]

But we want to turn ["name1", "Angle"] into an object like { name1: "Angle" }.

The most straightforward way of expressing this would be:

Object.entries(input).map(entry => {
   return { [entry[0]]: entry[1] };
}

The only tricky part in the syntax above is creating a dynamic property name based on a variable with the syntax { [key]: value }. We want a property named entry[0] with the value in entry[1] and { [entry[0]]: entry[1] } will do that.

But we can make use of some destructuring and return the object from the arrow function directly.

destructuring. Rather than using entry as the parameter, we can destructure this short 2-element array into the key and value immediately. Although it's tempting to write [k, v] => you must enclose it in parentheses like ([k, v]) => .

returning an object from an arrow function. It's also tempting to return an object literal like => { name1: "Angle" } but again, that's ambiguous (looks like a code block) so we have to enclose the object literal with parentheses: => ({ name1: "Angle" })

All those extra parentheses are unfortunately necessary. The whole thing looks like:

Object.Entries(input).map(([k, v]) => ({ [k]: v }));

So perhaps you may find the destructuring syntax is clunky because of the parentheses. Instead you can use Object.keys. Object.keys(input) returns:

[
  "name1",
  "name2",
  "name3"
]

We can map each property name to the desired object like this .map(k => ({ [k]: input[k] })) Which saves us a little bit of destructuring syntax awkwardness at the cost of having to specify the array by its name again.

This is likely the fastest way, if the number of properties is large, because it should use fewer allocations and intermediate objects.

Alternate approach with a loop

There is another way, using a loop, and it's faster than both of the above if the number of properties is very small.

const input = { "name1": "Angle", "name2": "Demon", "name3": "Hunter" };
const result = [];
for (let key in input) result.push({ [key]: input[key] });
console.log(result);

(This actually performs best on your tiny test data, I found.)

But I personally prefer functional constructs over imperative constructs because it gives the compiler the opportunity to do something more efficient than a loop. I believe we should teach the next generation of programmers to embrace modern ways of describing programs, and loops are passé in that regard.

Upvotes: 0

PeterKA
PeterKA

Reputation: 24638

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

Upvotes: 1

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27192

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

Upvotes: 1

Related Questions