-1

Screenshot of console

I have a JSON object, color, that consists of two JSON objects. I need to transfer these two JSON objects to an array. How can I do that?

i.e. {blue, purple} to [blue, purple]

Morgan4568771
  • 153
  • 2
  • 4
  • 14

2 Answers2

1

The need for this is probably a code smell, but here you go:

const colorObject = {
  blue: { "foo": "bar" },
  purple: { "baz": "qum" }
};

const colorArray = Object.keys(colorObject).map(k => colorObject[k]);

console.log(colorArray);

As James Thorpe mentions in the comment above, if you can do this once without keeping the array around, that's preferable.

shabs
  • 718
  • 3
  • 10
  • 1
    You dont need a `push` within a `map` - it'll do that all by itself with `.map(k => colorObject[k])` – Jamiec Jun 13 '17 at 15:35
1

Solution

let obj = {blue: {foo: 'bar'}, purple: {baz: 'qux'}};

let arr = Object.keys(obj).map(key => obj[key]);

console.log(arr);
Shammel Lee
  • 4,092
  • 1
  • 17
  • 20