gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:56:14 25 4
gpt4 key购买 nike

默认对象是:

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}
];

最佳答案

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

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

关于javascript - 将对象复制到具有特定条件的另一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38802543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com