[英]Filtering objects from array lodash
I have an Array like this 我有一个这样的数组
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"}
]
Using lodash i would like to remove description, category_ids, required_options, has_options
from it to look like 我想使用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"}
]
I tried something like this 我尝试过这样的事情
const filter = _(customAttributes)
.keyBy('attribute_code')
.pullAt(['description', 'category_ids', 'required_options', 'has_options'])
.value();
But this is returning 但这又回来了
[
{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"},
]
as _.at, i guess its not mutating the array. 作为_.at,我想它不会改变数组。 What am i doing wrong here?
我在这里做错了什么? I just cant figure it out.
我只是想不通。
Assuming that your original array is stored in data
, 假设原始数组存储在
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"}
]
You can filter out unwanted elements with filter
function: 您可以使用
filter
功能过滤掉不需要的元素:
var toRemove = new Set([
"description",
"category_ids",
"required_options",
"has_options"
])
_(data).filter(e => !toRemove.has(e.attribute_code)).value()
Also, this can be done without lodash. 同样,这也可以做到没有破折号。
data.filter(e => !toRemove.has(e.attribute_code))
You can use dropWhile()
您可以使用
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.