javascript - Javascript map add value to exist key
问题描述
Hello I've got problem with map in js, I've got list of orders in form like this=>
const ORDERS = [
{
orderId:1,
category:"sport",
amount:350,
time:'2019-12-15T19:23:30.000Z'
},
{
orderId:2,
category:"sport",
amount:350,
time:'2019-12-15T19:21:30.000Z'
},
{
orderId:3,
category:"garden",
amount:120,
time:'2019-12-15T19:25:30.000Z'
},
{
orderId:4,
category:"sport",
amount:250,
time:'2019-12-15T19:23:30.000Z'
}
]
I want to create map key based on unique category and amount and map value is a array with times. For example reffered to above order list: key: {category:'Sport',amount:350} and value: [{'2019-12-15T19:23:30.000Z'},{'2019-12-15T19:21:30.000Z'}], key:{category:'Sport',amount:250} and value: [{'2019-12-15T19:23:30.000Z'}] key:{category:'garden',amount:120} and value: [{'2019-12-15T19:25:30.000Z'}]
But when I iterate in for loop then always create new key with this same specific like before. I want to add only new value(time) to exist key.
export const duplicateOrders = (orders = []) => {
let orderMap = new Map();
for(let i = 0 ; i<= orders.length-1; i++){
let key = [orders[i].category,orders[i].amount];
let value = orders[i].time;
if(!orderMap.has(key)){
orderMap.set(key,value);
} else{
let old = orderMap.get(key);
orderMap.set(key,(old + value));
}
}
these are my scribbles without desirable result
解决方案
使用两层对象映射来跟踪两个键。使用 Object.values 和 flatMap 展开。
注意:创建生成的连接密钥的其他答案应该足够了,除非您在密钥序列化方面遇到一些问题导致冲突。
const collector = os=>Object.values(os.reduce(
(acc,{category:key, amount, time})=>{
const hasTime = acc?.[key]?.[amount]?.time;
if( typeof hasTime === 'undefined' )
acc[key] = {...acc[key], [amount]: {key, amount, time: [time] }};
else acc[key][amount].time.push(time);
return acc;
},{}
)).flatMap(x=>Object.values(x));
const ORDERS = [
{
orderId:1,
category:"sport",
amount:350,
time:'2019-12-15T19:23:30.000Z'
},
{
orderId:2,
category:"sport",
amount:350,
time:'2019-12-15T19:21:30.000Z'
},
{
orderId:3,
category:"garden",
amount:120,
time:'2019-12-15T19:25:30.000Z'
},
{
orderId:4,
category:"sport",
amount:250,
time:'2019-12-15T19:23:30.000Z'
}
]
console.log(
collector(ORDERS)
);
推荐阅读
- javascript - 在节点js中循环回调函数
- python - How to make the inputs and model have the same shape (RLlib Ray Sagemaker reinforcement learning)
- java - 在使用 sql2o 关闭连接之前执行更多查询
- vba - 在 Eval 中省略函数参数
- rest - 术语问题:API 介于 SOAP 和 REST 之间——它们的名称是什么?
- c# - 将数据从正在运行的 C++ exe 共享到 .NET 应用程序的推荐方法,最好是 WCF 服务
- uitableview - 在 tableView 单元格中拖放
- excel - 浮点计算的结果在 excel 和 python 中不同
- reactjs - React:如何让 useEffect reducer 函数与 react-datepicker 一起工作?
- esp32 - 从 WiFi 到 ESP32 上的蜂窝 3/4G