我有一个问题。我有一个对象数组,我想将数组中每个对象的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
}})
但是这似乎是一种不好的方法,我的意思是如果对象具有更多的值,我必须在地图中重复它们。是否有更好的方法呢?
谢谢
答案 0 :(得分:3)
如果要修改现有对象,只需更新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 数组中创建 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;
}