简体   繁体   English

在 JavaScript 中尝试从 3 个数组对象创建字典 - 挑战问题

[英]In JavaScript trying to create dictionary from 3 array objects - Challenge Question

I am trying to create dictionary with 3 different arrays我正在尝试用 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"]

Also from above example I want remove the duplicate of "Items", if "Units" are same;同样从上面的示例中,如果“单位”相同,我想删除“项目”的重复项; ie Salt repeating twice (1 gms and 2 gms), it should be { Salt: '3 gms'}即盐重复两次(1 gms 和 2 gms),它应该是 { Salt: '3 gms'}

If units are different then it should be repated twice, ie Pepper repeating twice with different units( 1 gms and 2 pound), it should be {Pepper: '1 gms', Pepper: '2 pound'}如果单位不同,则应重复两次,即胡椒以不同的单位(1 克和 2 磅)重复两次,则应为 {Pepper: '1 gms', Pepper: '2 pound'}

Example code示例代码

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' }

You can't have duplicate keys in an object.对象中不能有重复的键。 Put the values in an array.将值放入数组中。

 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)

I achieved something similar but without the duplicate keys (which you can handle by your own)我实现了类似的东西,但没有重复的键(你可以自己处理)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM