我有2个数组。比方说
categories = ["hotels", "transfers","food","transfers"]
amounts = [1500, 250, 165, 150]
我想生成一个输出对象的对象...
result = {hotels: 1500, transfers: 400, food: 165}
该函数应遍历类别,填充结果对象,将类别的唯一元素添加为对象键,并将量添加为值。该功能还应添加重复键的数量。
我已经尝试了几种方法,例如在数组上为每个嵌套2个循环,...但是我无法找出任何可行的方法...
最佳答案
如果两个数组的索引始终保持同步,则可以执行以下操作:
const categories = ["hotels", "transfers","food","transfers"];
const amounts = [1500, 250, 165, 150];
const result = {};
categories.forEach((category, index) => {
const doesKeyExist = !!result[category];
const amount = amounts[index];
const correctAmount = doesKeyExist ? result[category] + amount : amount;
result[category] = correctAmount;
}
这将导致您期望的结果:
result = {hotels: 1500, transfers: 400, food: 165}