【问题标题】:Taking action in javascript object on duplicate key在 javascript 对象中对重复键执行操作
【发布时间】:2018-04-09 15:31:46
【问题描述】:

我有一个非常混乱的 js 对象,我正在尝试清理它。 我是否需要创建一个新对象,我将在每个重复键出现时添加一个新元素?

基本上,我正在尝试转向:

[ { device: 4323, action: 'CASH IN' },
  { device: 4325, action: 'ALTER DB' },
  { device: 4323, action: 'Order Pizza' } ]

进入:

[ { device: 4323, action: 'CASH IN, Order Pizza' },
  { device: 4325, action: 'ALTER DB' } ]

【问题讨论】:

    标签: javascript json node.js object


    【解决方案1】:

    使用array.reduce:

    var items = [ { device: 4323, action: 'CASH IN' },
      { device: 4325, action: 'ALTER DB' },
      { device: 4323, action: 'Order Pizza' } ];
      
    var res = items.reduce((m, o) => {
      var found = m.find(e => e.device === o.device);
      found ? found.action += `, ${o.action}` : m.push(o);
      return m;
    }, []);
    
    console.log(res);

    【讨论】:

      【解决方案2】:

      尝试关注

      var arr = [ { device: 4323, action: 'CASH IN' },
        { device: 4325, action: 'ALTER DB' },
        { device: 4323, action: 'Order Pizza' } ];
        
        var map = {}; // map stores key as device and value as index of array
        var counter = 1; // counter to manage index
        var result = []; // the result array
        arr.forEach(function(item){ // iterating over array
          if(map[item.device]) { // check for existence of device in map
            // if exists only update its action in array
            result[map[item.device] - 1].action =  result[map[item.device] - 1].action + ", " + item.action; 
          } else { // if does not exist, set device in map and push object in result array
            map[item.device] = counter++;
            result.push(item);
          }
        });
        
        console.log(result);

      【讨论】:

        猜你喜欢
        • 2015-12-29
        • 2016-07-04
        • 1970-01-01
        • 2021-11-24
        • 2014-08-21
        • 2011-12-11
        • 1970-01-01
        • 1970-01-01
        • 2011-03-30
        相关资源
        最近更新 更多