Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert javascript array to specific list of objects

Tags:

javascript

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)
}
like image 474
Prashant Pimpale Avatar asked Dec 13 '22 13:12

Prashant Pimpale


1 Answers

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)
like image 170
Mark Avatar answered Feb 23 '23 01:02

Mark