简体   繁体   English

将对象数组转换为数组对象

[英]Convert array of objects to an object of arrays

I have the following structure 我有以下结构

var nights = [
    { "2016-06-25": 32, "2016-06-26": 151, "2016-06-27": null },
    { "2016-06-24": null, "2016-06-25": null, "2016-06-26": null },
    { "2016-06-26": 11, "2016-06-27": 31, "2016-06-28": 31 },
];

And I want to transform it to: 我想将其转换为:

{ 
    "2016-06-24": [null], 
    "2016-06-25": [32, null], 
    "2016-06-26": [151, null, 11], 
    "2016-06-27": [null, 31], 
    "2016-06-28": [31] 
}

What's the shortest way to solve this? 解决这个问题的最短方法是什么? I have no problems with using Underscore, Lodash or jQuery. 使用Underscore,Lodash或jQuery我没有问题。

My current code is: 我当前的代码是:

var out = {};
for (var i = 0; i < nights.length; i++) {
    for (var key in nights[i]) {
        if (out[key] === undefined) {
            out[key] = [];
        }
        out[key].push(nights[i][key]);
    }
}

It's similar to Convert array of objects to object of arrays using lodash but that has all keys present in each object. 它类似于使用lodash将对象数组转换为数组对象,但是每个对象中都包含所有键。

You can do it with the following snippet (no need for lodash etc): 您可以使用以下代码段(不需要lodash等)完成此操作:

 const x = [{ '2016-06-25': 32, '2016-06-26': 151, '2016-06-27': null }, { '2016-06-24': null, '2016-06-25': null, '2016-06-26': null }, { '2016-06-26': 11, '2016-06-27': 31, '2016-06-28': 31 }, ]; let y = {}; x.forEach(obj => { Object.keys(obj).forEach(key => { y[key] = (y[key] || []).concat([obj[key]]); }); }); console.log(y) 

You could iterate over the array and the over the keys of the object and build a new object with the keys as new keys. 您可以遍历数组和对象的键,并使用键作为新键构建新对象。

 var data = [{ '2016-06-25': 32, '2016-06-26': 151, '2016-06-27': null }, { '2016-06-24': null, '2016-06-25': null, '2016-06-26': null }, { '2016-06-26': 11, '2016-06-27': 31, '2016-06-28': 31 }, ], result = {}; data.forEach(function (o) { Object.keys(o).forEach(function (k) { result[k] = result[k] || []; result[k].push(o[k]); }); }); console.log(result); 

Used Typescript -- obviously you can remove the types while working in JavaScript. 使用的打字稿-显然,您可以在使用JavaScript时删除这些打字稿。

Assumption: The array of objects coming into the function will always have the same kind and number of object keys 假设:进入函数的对象数组将始终具有相同种类和数量的对象键

mapperArrayOfJsonsToJsonOfArrays(inputArrayOfJsons: any): any {
    if (inputArrayOfJsons.length > 0) {
        let resultMap = {};
        let keys: any[] = Object.keys(inputArrayOfJsons[0]);
        keys.forEach((key: any) => {
            resultMap[key] = [];
        });

        inputArrayOfJsons.forEach((element: any) => {
            let values: any[] = Object.values(element);
            let index = 0;
            values.forEach((value: any) => {
                resultMap[keys[index]].push(value);
                index = index + 1;
            });
        });
        return resultMap;
    }
    return {};
}

Here is my one-liner. 这是我的班轮。 Uses map to map keys into array of objects with properties of the keys. 使用map将键映射到具有键属性的对象数组。 Then maps the original array to only that property and sets it as the value of the property. 然后将原始数组仅映射到该属性,并将其设置为该属性的值。 One issue with this way is that it will only use the properties of the first object in the array. 这种方法的一个问题是,它将仅使用数组中第一个对象的属性。 So if other objects have properties that aren't in the first object they will be ignored. 因此,如果其他对象的属性不在第一个对象中,则将忽略它们。

const output = Object.assign({}, ...Object.keys(input[0]).map(props => ({[props]: input.map(prop => prop[props])})))

Edit: the output was in the wrong format, fixed 编辑:输出格式错误,已修复

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

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