首页 > 解决方案 > 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

标签: javascriptdictionary

解决方案


使用两层对象映射来跟踪两个键。使用 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)
);


推荐阅读