[英]I have two arrays, with the same values in the first array as in the ID fields of the second array
What I want to achieve is to have a third array with an output seen at the bottom from two other arrays.我想要实现的是让第三个阵列在底部看到一个 output,另外两个 arrays。
Now the key here is that it is basically a filter based on the Object.keys array matches from the mapped array.现在这里的关键是它基本上是一个基于映射数组中 Object.keys 数组匹配项的过滤器。 Meaning any id that exists in the mapped array and the Object.keys array should go into the third array.
这意味着映射数组中存在的任何 id 和 Object.keys 数组应该 go 进入第三个数组。
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.我越想越觉得我需要对映射数组进行过滤,只是不能 100% 确定如何正确地实现它。 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.我也尝试过使用 findIndex 来查找匹配的 ID,但它似乎没有找到匹配项。
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)
这是
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第三阵列 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:只需检查
id
是否在filter
谓词的键数组中:
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:虽然我不确定你为什么不跳过 object 键到数组映射并只检查原始的 object,这比检查一个项目是否在数组中更有效:
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如果
cartDetails
可以/可能包含有效的假值,如 0、空字符串或假
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.