Search code examples
javascriptlodash

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

[
 {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. What am i doing wrong here? I just cant figure it out.


Solution

  • Assuming that your original array is stored in 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:

    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))