简体   繁体   中英

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.

PS Is there any way to do this without using for loop ?

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} }
//=> ]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM