从数组lodash过滤对象

时间:2018-02-21 08:24:39

标签: javascript 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,我猜它不会改变数组。我在这做错了什么?我只是想不通。

2 个答案:

答案 0 :(得分:1)

假设您的原始数组存储在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()

此外,这可以在没有lodash的情况下完成。

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

答案 1 :(得分:1)

您可以使用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>