简体   繁体   English

将 object 转换为单个键/值对象的数组

[英]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.所以显然我想使用真正的密钥而不是key作为我在arr中封装的json的密钥。

PS Is there any way to do this without using for loop ? PS有没有办法在不使用for循环的情况下做到这一点?

Your issue is here:你的问题在这里:

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

In this context key is literally the name of the property.在这种情况下, key实际上是属性的名称。 However what you are looking for is to evaluate key as the name of your property (aka computed property name ):但是,您正在寻找的是评估key作为您的属性的名称(又名计算的属性名称):

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.您可以使用给定的键将分离的键/值对带到新的 object 中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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