[英]In JavaScript trying to create dictionary from 3 array objects - Challenge Question
我正在嘗試用 3 個不同的數組創建字典
myItems = ["Salt", "Pepper", "Oil", "Salt", "Pepper", "Oil", "Onion"]
myQuantities = [1, 1, 1, 2, 2, 2, 2]
myUnits = ["gms", "gms", "kgs", "gms", "pound", "kgs", "pound"]
同樣從上面的示例中,如果“單位”相同,我想刪除“項目”的重復項; 即鹽重復兩次(1 gms 和 2 gms),它應該是 { Salt: '3 gms'}
如果單位不同,則應重復兩次,即胡椒以不同的單位(1 克和 2 磅)重復兩次,則應為 {Pepper: '1 gms', Pepper: '2 pound'}
示例代碼
myItems = ["Salt", "Pepper", "Oil", "Salt", "Pepper", "Oil", "Onion"]
myQuantities = [1, 1, 1, 2, 2, 2, 2]
myUnits = ["gms", "gms", "kgs", "gms", "pound", "kgs", "pound"]
console.log(myItems);
console.log(myQuantities);
console.log(myUnits);
let final = Object.fromEntries(
myItems.map((_, i) => [myItems[i], myQuantities[i].toString()+" "+myUnits[i]])
);
console.log(final)
Current Result = { Salt: '2 gms', Pepper: '2 pound', Oil: '2 kgs', Tes: '2 pound' }
Expected Result = { Salt: '3 gms', Pepper: '1 gms', Pepper: '2 pound', Oil: '3 kgs', Tes: '2 Onion' }
對象中不能有重復的鍵。 將值放入數組中。
const myItems = ["Salt", "Pepper", "Oil", "Salt", "Pepper", "Oil", "Onion"] const myQuantities = [1, 1, 1, 2, 2, 2, 2] const myUnits = ["gms", "gms", "kgs", "gms", "pound", "kgs", "pound"] let final = {} myItems.forEach((item, i) => { if (!final[item]) { final[item] = []; } final[item].push(myQuantities[i] + " " + myUnits[i]); }); console.log(final)
我實現了類似的東西,但沒有重復的鍵(你可以自己處理)
let myItems = ["Salt", "Pepper", "Oil", "Salt", "Pepper", "Oil", "Onion"]
let myQuantities = [1, 1, 1, 2, 2, 2, 2]
let myUnits = ["gms", "gms", "kgs", "gms", "pound", "kgs", "pound"]
let x = myItems.reduce((newObj, entry, idx) =>{
if(!newObj[entry]){
newObj[entry] = [myQuantities[idx], myUnits[idx]];
} else {
if(newObj[entry][1] == myUnits[idx]){
newObj[entry] = [(newObj[entry][0] + myQuantities[idx]), myUnits[idx]];
} else {
// should convert unit here or handle the case properly
}
}
return newObj;
}, {});
Object.keys(x).forEach(ele => x[ele] = x[ele][0] + ' ' + x[ele][1]);
console.log(x);
//result: {Salt: "3 gms", Pepper: "1 gms", Oil: "3 kgs", Onion: "2 pound"}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.