HappyCoding HappyCoding - 4 months ago 15
Javascript Question

Copying an object to another object with specific condition

The default object is:

var employee = {
'name': 'Hermione',
'salary': 1000
};


My question is, how to copy that to another object with this formatting?

var employee = {
'Hermione': 1000
};


I've tried:

for (var prop in employee) {
console.log(prop, employee[prop]); // 'name' 'Hermione'
// what next?
}


UPDATE:

var employees = [];
employees.push({ 'name': 'name1', 'salary': 1000 });
employees.push({ 'name': 'name2', 'salary': 2000 });
employees.push({ 'name': 'name3', 'salary': 3000 });


What I want to achieve:

var employees = [
{'name1': 1000},
{'name2': 2000},
{'name3': 3000}
];

Answer

Do you have an array of those objects? For single object the case is rather simple:

var employee2 = {};
employee2[employee['name']] = employee['salary'];

or for modern browsers:

var employee2 = {
    [employee['name']]: employee['salary']
};

update

for array of objects:

var employees = [
  { name: 'name1', salary: 1000 },
  { name: 'name2', salary: 2000 },
  { name: 'name3', salary: 3000 }
];

var employees2 = employees.map(employee => ({[employee.name]: employee.salary}));

console.dir(employees2);

for older browsers:

var employees2 = employees.map(function(employee) {
     var result = {};
     result[employee['name']] = employee['salary'];
     return result;
});