i have an array that looks like this
let arrayExample =
[
{
"size":"6M",
"color":"Blue"
}
,
{
"size":"2M",
"color":"Yellow"
}
]
currently, to return all elements of a specific color or a specific size I use this approach
var allColors= arrayExample.map(i=>i.color)
return [{"color":"Blue"}].some((val)=> allColors.includes(val.color))
my question is how to return only elements that contain an exact combination of color and size
my current approach to this is
var allColors= arrayExample.map(i=>i.color)
var allSizes= arrayExample.map(i=>i.size)
return [{"color":"Blue","size":"2M"}].some((val)=> allColors.includes(val.color) && allSizes.includes(val.size)
this approach doesn't work for my purposes, knowing that even if there is no item in my arrayExample
with the combination [{"color":"Blue","size":"2M"}]
, it would still return true
because of the 2M size of the 2nd item of my array
here is a Jsfiddle to test my situation https://jsfiddle.net/8htjpyb9/
I would like to thank you if you got this far and also thank you for any and all help, I hope you are having a good day
CodePudding user response:
- Using
Array#filter
, iterate over the array - In every iteration, using
Array#some
, check if any of thecombinations
match the current object. - To do so, you can use
Object#entries
andArray#every
to check a combination of properties matching the current object.
const array = [ { "size": "6M", "color": "Blue" }, { "size": "2M", "color": "Yellow" } ];
const combinations = [{"color": "Blue", "size": "2M"}];
const matches = array.filter(current =>
combinations.some(combination =>
Object.entries(combination).every(([key, value]) =>
current[key] === value
)
)
);
console.log(matches);
CodePudding user response:
If I understand correctly you are looking for this?
const getItem = (arr, toFind) => {
const {size, color} = toFind;
return arr.filter(item => item.color === color && item.size === size)
};
let arrayExample = [{
"size": "6M",
"color": "Blue",
"material": "plastic"
},
{
"size": "2M",
"color": "Yellow",
"material": "leather"
}
]
const res = getItem(arrayExample,{"size": "6M","color": "Blue"})
console.log(res)
CodePudding user response:
filter
would be an easier approach. Pass in a set of data, and a test object to a function and return only those object that have the same size and colour values as the test object.
const data=[{id: 1,size:'6M',color:'Blue'},{ld:2,size:'2M',color:'Yellow'},{id:3,size:'6M',color:'Blue'}];
const test = { size: '6M', color: 'Blue' };
function getExact(data, test) {
return data.filter(obj => {
return (
obj.size === test.size
&& obj.color === test.color
);
});
}
console.log(getExact(data, test));