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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With