gpt4 book ai didi

javascript - jquery中查找数组和对象的公共(public)键

转载 作者:行者123 更新时间:2023-12-03 01:02:43 25 4
gpt4 key购买 nike

我有 2 个具有相似值的数组。我想要的是获得数组和对象的交集 -

第一个对象的 console.log 是 -

{  
"1221":{
"oldPrice":{
"amount":75
},
"basePrice":{
"amount":75
},
"finalPrice":{
"amount":75
},
"tierPrices":[

]
},
"1222":{
"oldPrice":{
"amount":75
},
"basePrice":{
"amount":75
},
"finalPrice":{
"amount":75
},
"tierPrices":[

]
},
"1223":{
"oldPrice":{
"amount":75
},
"basePrice":{
"amount":75
},
"finalPrice":{
"amount":75
},
"tierPrices":[

]
},
"1224":{
"oldPrice":{
"amount":80
},
"basePrice":{
"amount":80
},
"finalPrice":{
"amount":80
},
"tierPrices":[

]
}
}

第二个数组的 console.log 是 -

[["1222","1223","1224"]]

基本上,我想获取第一个对象,其 ids 等于第二个数组,即 1222、1223 和 1224。

我尝试过使用inArray,但它不起作用。

最佳答案

您可以使用Array.reduceObject.assign

let obj = {"1221":{"oldPrice":{"amount":75},"basePrice":{"amount":75},"finalPrice":{"amount":75},"tierPrices":[]},"1222":{"oldPrice":{"amount":75},"basePrice":{"amount":75},"finalPrice":{"amount":75},"tierPrices":[]},"1223":{"oldPrice":{"amount":75},"basePrice":{"amount":75},"finalPrice":{"amount":75},"tierPrices":[]},"1224":{"oldPrice":{"amount":80},"basePrice":{"amount":80},"finalPrice":{"amount":80},"tierPrices":[]}};

let arr = [["1222","1223","1224"]];

let result = arr[0].reduce((a,c) => Object.assign(a, {[c] : obj[c]}), {});
console.log(result);

注意:如果array中有一个条目在object中丢失,您可以将代码更新为以下

let obj = {"1221":{"oldPrice":{"amount":75},"basePrice":{"amount":75},"finalPrice":{"amount":75},"tierPrices":[]},"1222":{"oldPrice":{"amount":75},"basePrice":{"amount":75},"finalPrice":{"amount":75},"tierPrices":[]},"1223":{"oldPrice":{"amount":75},"basePrice":{"amount":75},"finalPrice":{"amount":75},"tierPrices":[]},"1224":{"oldPrice":{"amount":80},"basePrice":{"amount":80},"finalPrice":{"amount":80},"tierPrices":[]}};

let arr = [["missing_entry_from_obj", "1222","1223","1224"]];

let result = arr[0].reduce((a,c) => {if(obj[c]) a[c]= obj[c]; return a;}, {});
console.log(result);

关于javascript - jquery中查找数组和对象的公共(public)键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52556240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com