IsaIkari
IsaIkari

Reputation: 1154

Transform an object into an array of single key/value objects

I have this variable:

let json1 = 
{'aaa': {'cus1':1,'cus2':2},
 'bbb': {'cus3':1,'cus4':5}
}

And I would like to convert it into the following array:

[{'aaa': {'cus1':1,'cus2':2}},
 {'bbb': {'cus3':1,'cus4':5}}
]

What I tried to do is:

let arr = [];
let keys = Object.keys(json1);
keys.reduce((acc, key) => {
        acc.push({key: json1[key]});
        return acc;
    }, arr);

While I get:

[ { key: { cus1: 1, cus2: 2 } }, { key: { cus3: 1, cus4: 5 } } ]

So evidently I would like to use the true key instead of key as the key of my encapsulated json in the arr.

P.S. Is there any way to do this without using for loop?

Upvotes: 0

Views: 70

Answers (2)

customcommander
customcommander

Reputation: 18901

Your issue is here:

acc.push({key: json1[key]});
//        ^
//        here

In this context key is literally the name of the property. However what you are looking for is to evaluate key as the name of your property (aka computed property name):

acc.push({[key]: json1[key]});
//        ^
//        now your property name is whatever `key` value is

A simple example:

var key = '🌯';
var obj = {[key]: true};

obj;
//=> { "🌯": true }

Now to answer your question:

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

split({ aaa: {cus1: 1, cus2: 2}
      , bbb: {cus3: 1, cus4: 5}
      });

//=> [ { aaa: {cus1: 1, cus2: 2} }
//=> , { bbb: {cus3: 1, cus4: 5} }
//=> ]

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386550

You could take the separated key/value pair to a new object with the given key.

const
    data = { aaa: { cus1: 1, cus2: 2 }, bbb: { cus3: 1, cus4: 5 } },
    array = Object.entries(data).map(([k, v]) => ({ [k]: v }));
    
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions