Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

javascript - 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...