0

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'}
             ]
3
  • 1
    Welcome to Stack Overflow! Please take the tour if you haven't already (you get a badge!) and read through the help center, in particular How do I ask a good question? Your best bet here is to do your research, search for related topics on SO and elsewhere, and give it a go. If you get stuck and can't get unstuck after doing more research and searching, post a minimal reproducible example showing your attempt and say specifically where you're stuck. People will be glad to help. Commented Apr 4, 2022 at 13:04
  • 1
    But separately, having an array of objects where each object has different property names is generally not a good idea. It would make more sense to use the name name rather than name1, name2, and name3. Commented Apr 4, 2022 at 13:05
  • Are you aware of Object.entries? Commented Apr 4, 2022 at 13:52

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Or just const res = Object.keys(result).map(item => ({ [item]: result[item] }));
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.