简体   繁体   中英

Remove objects from an array using underscore js or lodash

I want to remove an object contains 'twitter' from the 'contents' array using underscore js.

contents = 
[
  {
     "facebook": "test",
     "preview_image_url": "url",
     "preview_title": "title",
     "preview_description": "description"
  },
  {
     "twitter": "test",
     "preview_image_url": ""
  }
]

Expecting result array as follows

contents = 
[
  {
     "facebook": "test",
     "preview_image_url": "url",
     "preview_title": "title",
     "preview_description": "description"
  }
]

Your help is much appreciated.

In case you ever want a vanilla JS version:

var filtered = contents.filter(function (obj) {
  return Object.keys(obj).indexOf('twitter') === -1;
});

Or, taking on TJ's comment:

var filtered = contents.filter(function (obj) {
  return !obj.hasOwnProperty('twitter');
});

使用remove()

_.remove(contents, _.ary(_.partialRight(_.has, 'twitter'), 1));

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