4

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

4
  • 1
    how do you assign them? on what basis? Commented Jan 5, 2019 at 5:04
  • 2
    You sure the expected output is really what you want? I don't find any sense on it... Commented Jan 5, 2019 at 5:05
  • yes! On the basis of the employee name! they have their respective departments Commented Jan 5, 2019 at 5:08
  • If you need the respective departments on the basis of employee name, then shouldn't your result array be like [ { "Sushant" : [ "HR" , "DEV" ] } , { "Prashant" : [ "HR" , "MNGT" ] } ] Commented Jan 5, 2019 at 5:26

3 Answers 3

10

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.