简体   繁体   English

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

[英]How to convert javascript array to specific list of objects

I have an array like: 我有一个像这样的数组:

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

I want to convert this array into: 我想将此数组转换为:

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

I have tried with for loop and Object.values 我尝试过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) } 

You can loop over with reduce and add to the object at the correct index as you go. 您可以使用reduce循环,并在正确的索引处添加到对象。 Something like: 就像是:

 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) 

Here you have another approach using two nested forEach loops. 在这里,您可以使用两个嵌套的forEach循环。 Also, I have extended the dataset just to experiment with strange cases. 此外,我已经扩展了数据集,只是为了试验奇怪的情况。

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

However, this still have little sense for me, and I will go with something like this: 但是,这对我来说仍然没什么意义,我会用这样的东西:

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

This is not like what @Mark Meyer has written in sweet and short way (advanced one). 这与@Mark Meyer用甜言蜜语(高级版)写的不一样。

I am writing it for those who is not familiar with reduce() etc. but using array's methods like reduce() is really great and saves time. 我正在为那些不熟悉reduce()等的人编写它,但是使用像reduce()这样的数组方法真的很棒并节省时间。

Here is the code using loops, I don't recommend you to use this as this is for those situations where you want to use concept of loops, if-else etc. and you have time to code/think. 这是使用循环的代码,我不建议你使用它,因为这是你想要使用循环的概念,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"
        }
    ]
*/

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

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