想要从复杂对象中删除一些字段。
var obj1={title:"T1",name="name1",classes:[
{id:1,scheme:1,cName:"Cls1"},
{id:2,scheme:2,cName:"Cls2"},
{id:3,scheme:3,cName:"Cls3"},]}
我想从每个班级的班级中删除'scheme'和'cName'
答案 0 :(得分:3)
您可以在obj.classes
上使用map()
并整理要删除的属性,然后返回其他属性。
注意:以下方法将修改原始对象。
var obj1={title:"T1",name:"name1",classes:[ {id:1,scheme:1,cName:"Cls1"}, {id:2,scheme:2,cName:"Cls2"}, {id:3,scheme:3,cName:"Cls3"}]}
obj1.classes = obj1.classes.map(({cName,scheme,...rest}) => rest);
console.log(obj1);
如果只有三个属性scheme
,id
和cName
,并且您要删除其中两个。然后最好从map()
var obj1={title:"T1",name:"name1",classes:[ {id:1,scheme:1,cName:"Cls1"}, {id:2,scheme:2,cName:"Cls2"}, {id:3,scheme:3,cName:"Cls3"}]}
obj1.classes = obj1.classes.map(({id}) => ({id}));
console.log(obj1);
答案 1 :(得分:1)
将map()
与classes
属性一起使用。
map()
将根据您要获取的属性返回新数组。
如果要加入id
集合,只需执行以下代码:
var obj1={
title:"T1",
name: "name1",
classes: [
{id: 1, scheme: 1, cName: "Cls1"},
{id:2, scheme: 2, cName: "Cls2"},
{id:3, scheme: 3, cName: "Cls3"}
]
}
obj1.classes = obj1.classes.map((item) => item.id);
console.log(obj1)
答案 2 :(得分:0)
您可以这样做
let obj1={title:"T1",
name:"name1",
classes:[{id:1,scheme:1,cName:"Cls1"},
{id:2,scheme:2,cName:"Cls2"},
{id:3,scheme:3,cName:"Cls3"}]};
obj1.classes.forEach((el) => { delete el.scheme;
delete el.cName;});
console.log(obj1);