将对象复制到具有特定条件的另一个对象

时间:2016-08-06 09:10:19

标签: javascript object

默认对象是:

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

我的问题是,如何使用此格式将其复制到另一个对象?

var employee = {
    'Hermione': 1000
};

我试过了:

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

更新

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

我想要实现的目标:

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

3 个答案:

答案 0 :(得分:3)

你有这些对象的数组吗? 对于单个对象,情况相当简单:

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

或现代浏览器:

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

<强>更新

对象数组:

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

适用于旧浏览器:

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

答案 1 :(得分:1)

您应该使用Array.prototype.filterArray.prototype.map

var employees = [];
employees.push({ 'name': 'n1', 'salary': 1000 });
employees.push({ 'name': 'n2', 'salary': 2000 });
employees.push({ 'name': 'n3', 'salary': 3000 });

var reduced = employees
  .reduce((res, val) => {
    res[val.name] = val.salary;
    return res;
  }, Object.create(null))
;

console.log('reduced', reduced);

var mapped = employees
  .map(i => ({[i.name] : i.salary}))
;
console.log('mapped', mapped);

答案 2 :(得分:0)

newobj = {}; newobj [oldObj.name] = oldObj.salary