如果元素是数组,如何删除对象的元素?

时间:2019-05-15 09:27:14

标签: javascript lodash

想要从复杂对象中删除一些字段。

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'

3 个答案:

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

如果只有三个属性schemeidcName,并且您要删除其中两个。然后最好从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);