What I want to achieve is to have a third array with an output seen at the bottom from two other arrays.
Now the key here is that it is basically a filter based on the Object.keys array matches from the mapped array. Meaning any id that exists in the mapped array and the Object.keys array should go into the third array.
The more I think about the more it seems I need to do a filter on the mapped array, just not 100% certain how to achieve that properly. I did just try a filter now seen below and it returns an empty array.
I have also tried using a findIndex to find the matching id's but it doesn't seem to find matches.
Any help would be greatly appreciated
Thanks Kindly
const mapped = data.allProduct.map((item: any) => ({
slug: item.slug.current,
id: item.stripeId,
}));
// What I have tried
const foundMapped = mapped.findIndex(
(element: any, index: any) => element.id === Object.keys(cartDetails)[index]
);
const test = mapped.filter(
(item: any, index: any) => item.id === Object.keys(cartDetails)[index]
);
this is Object.keys(cartDetails)
[
"price_1KhMhhF2lAt0poJW42giHxDs",
"price_1KVisMF2lAt0poJWnd9LGheT",
"price_1KVisMF2lAt0poJWnd9fkfkf",
]
this is variable mapped from above
[
{
"slug": "the-void",
"id": "price_1KVisMF2lAt0poJWnd9LGheT"
},
{
"slug": "magic-wonders-artwork",
"id": "price_1KhMhhF2lAt0poJW42giHxDs"
},
{
"slug": "other-two",
"id": "price_1KVisMF2lAt0poJWnd9fkfkf"
},
{
"slug": "test-test",
"id": "price_1KVisMF2lAt0poJWnd9fjff"
}
]
Third Array Output
[
{
id: "price_1KhMhhF2lAt0poJW42giHxDs",
slug: "the-void"
},
{
id: "price_1KVisMF2lAt0poJWnd9LGheT",
slug: "magic-wonders-artwork"
},
{
id: "price_1KVisMF2lAt0poJWnd9fkfkf",
slug: "other-two"
},
]
just gotta check if the id is in the array of the keys in your filter predicate:
const keys = Object.keys(cartDetails);
const toFilter = data.allProduct.map((item: any) => ({
slug: item.slug.current,
id: item.stripeId,
}));
const filtered = toFilter.filter(i => keys.includes(i.id))
though I'm not sure why you wouldn't just skip the object keys to array mapping and just check the original object, which is more efficient than checking if an item is in an array:
const filtered = toFilter.filter(i => !!cartDetails[i.id])
or
const filtered = toFilter.filter(i => cartDetails[i.id] !== undefined)
if cartDetails can / might include valid falsey values like 0, empty string or false