Lodash Filter Matching For Multiple Values In Nested Objects
I have an array of objects const obj = [     {         'id': 20000,         'attributes': [             {                 'name': 'Size',                 'value': '38'
Solution 1:
Without a library, you could directly use Array#filter to obtain only specific elements.
Object.entries can be used to get the key-value pairs of the selected attributes, Array#every can be used to ensure that all entries match a given condition, and Array#some can be used to check that the key and value exist in the attributes array of the object.
const obj=[{id:2000,attributes:[{name:"Size",value:"38"},{name:"Color",value:"Blue"}]},{id:20056,attributes:[{name:"Size",value:"38"},{name:"Color",value:"Brown"}]}];
const selectedAttributes = {
    "Color": "Brown",
    "Size": "38"
}
const selectedAttributes2 = {
    "Size": "38"
}
constmatches = (arr, attrs)=>arr.filter(x =>Object.entries(attrs).every(([k, v])=>
    x.attributes.some(a => a.name === k && a.value === v
)));
console.log(matches(obj, selectedAttributes));
console.log(matches(obj, selectedAttributes2));.as-console-wrapper{max-height:100%!important;top:0}
Post a Comment for "Lodash Filter Matching For Multiple Values In Nested Objects"