I have a collection of objects structured as follows:
var items = [
{
itemId: 0,
itemQuantity: 10,
attributes: [
{ type: "Size", value: "Small" },
{ type: "Color", value: "Black" }
]
},
{
itemId: 1,
itemQuantity: 20,
attributes: [
{ type: "Size", value: "Small" },
{ type: "Color", value: "White" }
]
},
{
itemId: 2,
itemQuantity: 30,
attributes: [
{ type: "Size", value: "Medium" },
{ type: "Color", value: "Black" }
]
},
{
itemId: 3,
itemQuantity: 40,
attributes: [
{ type: "Size", value: "Medium" },
{ type: "Color", value: "White" }
]
}
];
In addition, I have a simple array containing the following elements:
let selectedAttributes = ["Small", "Black"];
The objective is to retrieve the parent object based on matching values from the nested array (attributes
). Specifically, I need to identify the object that contains both "Small" and "Black". The desired result should be:
let result = [
{
itemId: 0,
itemQuantity: 10,
attributes: [
{ type: "Size", value: "Small" },
{ type: "Color", value: "Black" }
]
}
]
Here is the current code snippet I am using. Upon logging the result, it returns an empty array:
let result = items.filter((item, index) => {
return item.attributes.some(attri => attri.value === selectedAttributes);
});
console.log(result);