如何将javascript数组转换为特定的对象列表

时间:2019-01-05 04:59:18

标签: javascript

我有一个像这样的数组:

[
  { "empName": "Sushant", "departments": ["HR","DEV"] },
  { "empName": "Prashant", "departments": ["HR","MNGT"] }
];

我想将此数组转换为:

[
 { "Sushant": "HR", "Prashant":"HR" },
 { "Sushant": "DEV", "Prashant":"MNGT" }
]

我已经尝试过for循环和Object.values

var data =     [
      { "empName": "Sushant", "departments": ["HR","DEV"] },
      { "empName": "Prashant", "departments": ["HR","MNGT"] }
    ];

for (var i = 0; i < data.length; i++) {
    var obj = Object.values(data[i]);
    console.log(obj)
}

3 个答案:

答案 0 :(得分:10)

您可以循环使用reduce并在正确的索引处添加到对象。像这样:

let arr = [{ "empName": "Sushant", "departments": ["HR","DEV"] },{ "empName": "Prashant", "departments": ["HR","MNGT"] }];

let a = arr.reduce((arr, {empName, departments}) => {
    departments.forEach((dept, i) => {
        arr[i] = Object.assign({[empName]: dept}, arr[i])
    })
    return arr
}, [])
console.log(a)

答案 1 :(得分:1)

在这里,您还有另一种使用两个嵌套forEach循环的方法。另外,我扩展了数据集只是为了试验奇怪的情况。

const data = [
    {"empName": "Sushant", "departments": ["HR","DEV"]},
    {"empName": "Prashant", "departments": ["HR","MNGT"]},
    {"empName": "Bob", "departments": ["ARTIST"]},
    {"empName": "Kevin", "departments": ["DEV", "MNGT", "HR"]},
    {"empName": "Alex", "departments": []},
    {"empName": "Mark"},
    {}
];

let output = [];

data.forEach((o, i) =>
{
    o.departments && o.departments.forEach((d, j) =>
    {
        output[j] = output[j] || {};
        output[j][[o.empName]] = d;
    });
});

console.log(output);

但是,这对我来说仍然意义不大,我会选择这样的内容:

const data = [
    {"empName": "Sushant", "departments": ["HR","DEV"]},
    {"empName": "Prashant", "departments": ["HR","MNGT"]}
];

let output = data.reduce((res, {empName, departments}) =>
{
    res[[empName]] = departments;
    return res;
}, {});

console.log(JSON.stringify(output));

// And you will have instant access to all the departments of a particular employee.

console.log("Deparments of Sushant: ", JSON.stringify(output.Sushant));
console.log("Deparments of Prashant: ", JSON.stringify(output.Prashant));

答案 2 :(得分:1)

这不像@Mark Meyer用简短的方式写的(高级)。

我是为不熟悉reduce()等的人编写的,但是使用reduce()这样的数组方法确实很棒,而且可以节省时间。

这是使用循环的代码,我不建议您使用此代码,因为这是用于那些需要使用循环,if-else等概念并且有时间进行编码/思考的情况。

let arr = [
     { "empName": "Sushant", "departments": ["HR","DEV"] },
     { "empName": "Prashant", "departments": ["HR","MNGT"] }
];

let newArr = [];

for(let obj of arr) {
    let name = obj.empName;
    let depts = obj.departments;


    if(newArr.length == 0) {
        for(let dept of depts) {
            newArr.push({[name]: dept});
        }
    } else {
        let j =0;
        for(let dept of depts) {
            newArr[j][name] = dept;
            ++j;
        }
    }
}

console.log(newArr);
/*
    [ { Sushant: 'HR', Prashant: 'HR' },
      { Sushant: 'DEV', Prashant: 'MNGT' } ]
*/

// Pretty printing
console.log(JSON.stringify(newArr, null, 4));
/*
    [
        {
            "Sushant": "HR",
            "Prashant": "HR"
        },
        {
            "Sushant": "DEV",
            "Prashant": "MNGT"
        }
    ]
*/