繁体   English   中英

从数组lodash过滤对象

[英]Filtering objects from array lodash

我有一个这样的数组

var data = [
 {attribute_code: "description", value: "<p>Description</p>"}, 
 {attribute_code: "category_ids", value: Array(2)},
 {attribute_code: "required_options", value: "0"},
 {attribute_code: "has_options", value: "0"},
 {attribute_code: "activity", value: "11,18,19,20,21,22,23"},
 {attribute_code: "material", value: "37,38"}
]

我想使用lodash删除description, category_ids, required_options, has_options使其看起来像

[
 {attribute_code: "activity", value: "11,18,19,20,21,22,23"},
 {attribute_code: "material", value: "37,38"}
]

我尝试过这样的事情

const filter = _(customAttributes)
    .keyBy('attribute_code')
    .pullAt(['description', 'category_ids', 'required_options', 'has_options'])
    .value();

但这又回来了

[
 {attribute_code: "description", value: "<p>Description</p>"}, 
 {attribute_code: "category_ids", value: Array(2)},
 {attribute_code: "required_options", value: "0"},
 {attribute_code: "has_options", value: "0"},
]

作为_.at,我想它不会改变数组。 我在这里做错了什么? 我只是想不通。

假设原始数组存储在data

var data = [
 {attribute_code: "description", value: "<p>Description</p>"}, 
 {attribute_code: "category_ids", value: Array(2)},
 {attribute_code: "required_options", value: "0"},
 {attribute_code: "has_options", value: "0"},
 {attribute_code: "activity", value: "11,18,19,20,21,22,23"},
 {attribute_code: "material", value: "37,38"}
]

您可以使用filter功能过滤掉不需要的元素:

var toRemove = new Set([
     "description",
     "category_ids",
     "required_options",
     "has_options"
])

_(data).filter(e => !toRemove.has(e.attribute_code)).value()

同样,这也可以做到没有破折号。

data.filter(e => !toRemove.has(e.attribute_code))

您可以使用dropWhile()

 var data = [{attribute_code: "description", value: "<p>Description</p>"},{attribute_code: "category_ids", value: Array(2)},{attribute_code: "required_options", value: "0"},{attribute_code: "has_options", value: "0"},{attribute_code: "activity", value: "11,18,19,20,21,22,23"},{attribute_code: "material", value: "37,38"}], removeParameters = ['description', 'category_ids', 'required_options', 'has_options'], result = _.dropWhile(data, ({attribute_code}) => removeParameters.includes(attribute_code)); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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