简体   繁体   中英

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

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

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.

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.

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"
        }
    ]
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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