我正在嘗試從variantCodesObject. 那部分我可以開始作業,但是我正在努力key從variantCodesObject.
cart array
[
{"ean": "7350038272416","quantity": 1},
{"ean": "7350038270276","quantity": 3}
]
variantCodesObject array
[
{ 261584049: "7350038272416" },
{ 261583813: "7350038274120" },
{ 261583424: "7350038270276" },
{ 261122928: "210000018685" },
]
cart.forEach(function (cartItem){
var ean = cartItem.ean;
var qty = cartItem.quantity;
if(variantCodesObject.indexOf(ean)){
makeSomeRequest(??, qty) //How do I get the key of the found EAN's here?
}
})
在上面的示例中,我如何獲得 ean7350038272416鍵值261584049?
我試過這樣的事情:
variantCodesObject.forEach(function(item){
if(item.indexOf(ean)){
Object.keys(item).forEach(function(key) {
console.log("key:" key "value:" item[key]);
});
}
});
但這會回傳完整的variantCodesObject.
uj5u.com熱心網友回復:
您可以通過根據每個購物車專案variantCodesObject的屬性檢查物件的值來執行此操作。.ean如果匹配,請用鑰匙做任何你想做的事
cart = [
{"ean": "7350038272416","quantity": 1},
{"ean": "7350038270276","quantity": 3}
]
variantCodesObject = [
{ 261584049: "7350038272416" },
{ 261583813: "7350038274120" },
{ 261583424: "7350038270276" },
{ 261122928: "210000018685" },
]
cart.forEach(item => {
variantCodesObject.forEach(obj => {
Object.entries(obj).forEach(([key, value]) => {
if (value === item.ean) {
console.log(key);
}
});
})
})
uj5u.com熱心網友回復:
一種方法是使用Array.reduce()從陣列中收集資料:
const cart =
[
{"ean": "7350038272416","quantity": 1},
{"ean": "7350038270276","quantity": 3}
]
const variantCodesObject =
[
{ 261584049: "7350038272416" },
{ 261583813: "7350038274120" },
{ 261583424: "7350038270276" },
{ 83424: "7350038270276" },
{ 261122928: "210000018685" },
]
cart.forEach(function (cartItem){
var ean = cartItem.ean;
var qty = cartItem.quantity;
const keys = variantCodesObject.reduce((ret, obj) =>
{
for(let key in obj)
if (obj[key] == ean)
ret[ret.length] = key;
return ret;
}, []);
console.log(ean, "=", keys);
})
uj5u.com熱心網友回復:
您可以創建一個“反向查找表”。這是您如何做到這一點的方法。
var cartArray = [
{ ean: '7350038272416', quantity: 1 },
{ ean: '7350038270276', quantity: 3 },
];
var variantCodesObjectArray = [
{ 261584049: '7350038272416' },
{ 261583813: '7350038274120' },
{ 261583424: '7350038270276' },
{ 261122928: '210000018685' },
];
// We are creating a lookup / dictionary by mapping the "EAN" to the "CODE"
var reverMappedCodesObjectArray = {};
variantCodesObjectArray.forEach(function (entry) {
var key = Object.keys(entry)[0];
reverMappedCodesObjectArray[entry[key]] = key;
});
cartArray.forEach(function (cartItem) {
var ean = cartItem.ean;
var qty = cartItem.quantity;
console.log(reverMappedCodesObjectArray[ean]);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/471371.html
標籤:javascript
