[英]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.