使用下划线 js 或 lodash 从数组中删除对象
Remove objects from an array using underscore js or lodash
我想使用下划线 js 从 'contents' 数组中删除包含 'twitter' 的对象。
contents =
[
{
"facebook": "test",
"preview_image_url": "url",
"preview_title": "title",
"preview_description": "description"
},
{
"twitter": "test",
"preview_image_url": ""
}
]
期望结果数组如下
contents =
[
{
"facebook": "test",
"preview_image_url": "url",
"preview_title": "title",
"preview_description": "description"
}
]
非常感谢您的帮助。
如果你想要一个普通的 JS 版本:
var filtered = contents.filter(function (obj) {
return Object.keys(obj).indexOf('twitter') === -1;
});
或者,接受 T.J 的评论:
var filtered = contents.filter(function (obj) {
return !obj.hasOwnProperty('twitter');
});
使用remove():
_.remove(contents, _.ary(_.partialRight(_.has, 'twitter'), 1));
我想使用下划线 js 从 'contents' 数组中删除包含 'twitter' 的对象。
contents =
[
{
"facebook": "test",
"preview_image_url": "url",
"preview_title": "title",
"preview_description": "description"
},
{
"twitter": "test",
"preview_image_url": ""
}
]
期望结果数组如下
contents =
[
{
"facebook": "test",
"preview_image_url": "url",
"preview_title": "title",
"preview_description": "description"
}
]
非常感谢您的帮助。
如果你想要一个普通的 JS 版本:
var filtered = contents.filter(function (obj) {
return Object.keys(obj).indexOf('twitter') === -1;
});
或者,接受 T.J 的评论:
var filtered = contents.filter(function (obj) {
return !obj.hasOwnProperty('twitter');
});
使用remove():
_.remove(contents, _.ary(_.partialRight(_.has, 'twitter'), 1));