将对象项映射到新值javascript



我有个问题。我有一个对象数组,我想将数组中每个对象的id大写。我用这些代码行

let x = [
{ id: "anc",path: "kdsfjdklsfj"},
{ id: "anc",path: "kdsfjdklsfj"},
{ id: "anc",path: "kdsfjdklsfj"},
]
x = x.map ( (a) => {return {
id :  a.id.toUpperCase(),
path : a.path
}})

但这看起来是一种糟糕的方法,我的意思是,如果对象有更多的值,我必须在地图中重复它们。有什么更好的方法吗?

感谢

如果您想修改现有对象,只需更新id:

x.forEach(a => a.id = a.id.toUpperCase());

实例:

let x = [
{ id: "anc",path: "kdsfjdklsfj"},
{ id: "anc",path: "kdsfjdklsfj"},
{ id: "anc",path: "kdsfjdklsfj"},
]
x.forEach(a => a.id = a.id.toUpperCase());
console.log(x);
.as-console-wrapper {
max-height: 100% !important;
}

如果您想在new数组中创建对象(您的代码当前所做的(,您可以使用ES2018的rest属性语法:

x = x.map(a => ({...a, id: a.id.toUpperCase()}));

实时示例(写入y而不是x以强调它是一个包含新对象的新数组(:

let x = [
{ id: "anc",path: "kdsfjdklsfj"},
{ id: "anc",path: "kdsfjdklsfj"},
{ id: "anc",path: "kdsfjdklsfj"},
]
let y = x.map(a => ({...a, id: a.id.toUpperCase()}));
console.log("x:", x);
console.log("y:", y);
.as-console-wrapper {
max-height: 100% !important;
}

要在不使用rest属性语法的情况下执行此操作,可以使用Object.assign:

let x = [
{ id: "anc",path: "kdsfjdklsfj"},
{ id: "anc",path: "kdsfjdklsfj"},
{ id: "anc",path: "kdsfjdklsfj"},
]
let y = x.map(a => Object.assign({}, a, {id: a.id.toUpperCase()}));
console.log("x:", x);
console.log("y:", y);
.as-console-wrapper {
max-height: 100% !important;
}

最新更新