简体   繁体   中英

Remove elements from array by name

I'd like to know how to remove boats from my array.

var obj = [
    { car: 1, boat: 2, plane: 3  },
    { car: 3, boat: 9, plane: 12  }
];


// Desired output
[
   { car: 1, plane: 3 },
   { car: 3, plane: 12 }
];

What I tried is to use Array.prototype.filter()

console.log(obj.filter(el => el (how to get el name) === 'boat'));

You're not removing elements from an array; instead you want to remove properties from existing objects, which happen to be array elements.

Use the delete operator to remove properties from objects. As you're not removing elements from an array you won't need to use filter either:

for( var i = 0; i < obj.length; i++ ) {
    delete obj[i]['boat'];
}

Just delete it

obj.forEach(function(el){
  delete el.boat;
})
//"[{"car":1,"plane":3},{"car":3,"plane":12}]"

If you want to create new array and not to modify your existing array:

var obj = [
    { car: 1, boat: 2, plane: 3  },
    { car: 3, boat: 9, plane: 12  }
];

var newArr = obj.map(e => ({car: e.car, plane: e.plane}));
// newArr = [{car: 1, plane: 3},{car: 3, plane: 12}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM