【问题标题】:How to stop duplicating keys for values如何停止为值重复键
【发布时间】:2018-05-08 17:48:29
【问题描述】:

我有一个数组序列号。它可能看起来像这样。

lot: 1  Serial: 2
lot: 1  Serial: 3
lot: 1  Serial: 4

... 等等。或者看起来像

lot: 1  Serial: 5
lot: 1  Serial: 9
lot: 8  Serial: 2
lot: 8  Serial: 4

var dictSerials = []
if (serialNumbers.length > 0) 
    for (var i of serialNumbers) {
        dictSerials.push({
            key: i.value.lot,
            value: i.value.serial
        })
    }

这是我试图用来让事情正常进行的方法,但这会为列出的每个项创建一个键和值。我希望我的结果是这样的对象:

Key: 1  Value: 2, 3, 4, 5, 9
Key: 8  Value: 2, 4

谁能帮我解决这个问题?谢谢!

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    满足您要求的另一种方法是使用函数reduce 对键和值进行分组。

    let array = [{lot: 1, Serial: 2},{lot: 1, Serial: 3},{lot: 1, Serial: 4},{lot: 1, Serial: 5},{lot: 1,Serial: 9},{lot: 8,Serial: 2},{lot: 8,Serial: 4}],
        result = Object.values(array.reduce((a, c) => {
          (a[c.lot] || (a[c.lot] = {Key: c.lot, Value: []})).Value.push(c.Serial);
          return a;
        }, {}));
        
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      【解决方案2】:

      不确定是否有更好/更简单的方法,但可以这样做:-

       var array = [{
            name: "foo1",
            value: "val1"
          }, {
            name: "foo1",
            value: ["val2", "val3"]
          }, {
            name: "foo2",
            value: "val4"
          }];
      
          var output = [];
      
          array.forEach(function(value) {
            var existing = output.filter(function(v, i) {
              return v.name == value.name;
            });
            if (existing.length) {
              var existingIndex = output.indexOf(existing[0]);
              output[existingIndex].value = output[existingIndex].value.concat(value.value);
            } else {
              if (typeof value.value == 'string')
                value.value = [value.value];
              output.push(value);
            }
          });
      
          console.dir(output);
      

      【讨论】:

        【解决方案3】:

        这是一个使用两个 forEach 循环的简单方法:

        const arr = [
          {lot : 1, Serial : 2},
          {lot : 1, Serial : 3},
          {lot : 1, Serial : 4},
          {lot : 1, Serial : 5},  
          {lot : 1, Serial : 9},
          {lot : 8, Serial : 2},
          {lot : 8, Serial : 4}
        ]
        
        let grouped = [],
          result = [];
        
        arr.forEach((e) => {
          (result[e.lot] || (result[e.lot] = [])).push(e.Serial)
        })
        
        result.forEach((e, i) => {
          grouped.push({
            "key": i,
            "value": e.join(',')
          })
        });
        
        console.log(grouped)

        【讨论】:

          【解决方案4】:

          您可以为此使用Map

          var serialNumbers = [
            {value:{lot:1, serial: 2}},
            {value:{lot:1, serial: 3}},
            {value:{lot:1, serial: 4}},
            {value:{lot:1, serial: 5}},
            {value:{lot:1, serial: 9}},
            {value:{lot:8, serial: 2}},
            {value:{lot:8, serial: 4}},
           ];
          
          var dictSerials = new Map();
          if (serialNumbers.length > 0) {
            for (var i of serialNumbers) {
                if(!dictSerials.has(i.value.lot)) {
                  dictSerials.set(i.value.lot, [i.value.serial]);        
                } else {
                  var v = dictSerials.get(i.value.lot);
                  v.push(i.value.serial);
                  dictSerials.set(i.value.lot, v);        
                }      
            }
          }
          //Output
          for (var [key, value] of dictSerials.entries()) {
            console.log("Key: " + key + " Value: " + value.join(","));
          }

          【讨论】:

            【解决方案5】:
            function getDictSerials(serialNumbers) {
            
                var dictSerials = {};
            
                if (serialNumbers.length > 0) {
                    for (let i of serialNumbers) {
                        let lot = i.lot;
                        let serial = i.serial;
            
                        if (!dictSerials[lot]) { // If the key isn't found - intiate an array
                            dictSerials[lot] = [];
                        }
            
                        dictSerials[lot].push(serial) // push the serial to the corresponding lot
                    }
                }
            
                return dictSerials;
            }
            
            let serialNumbers = [
                {lot : 1, serial : 2},
                {lot : 1, serial : 3},
                {lot : 1, serial : 4},
                {lot : 1, serial : 5},
                {lot : 1, serial : 9},
                {lot : 8, serial : 2},
                {lot : 8, serial : 4}
            ];
            
            let desiredObj =  {
                dictSerials: getDictSerials(serialNumbers)
            }
            
            JSON.stringify(desiredObj); // {"dictSerials":{"1":[2,3,4,5,9],"8":[2,4]}}
            

            【讨论】:

            • 我认为这里有一些东西,但是我们如何改变它,所以结果看起来像"dictSerials": [ { "key": "B7R52-47", "value": ["152426 SEG A", "152426 SEG B"] } ]
            【解决方案6】:
            var dictSerials = []
            if (serialNumbers.length > 0) {
                for (var i of serialNumbers) {
            
                  if(!dictSerials[i.value.lot]){
                      dictSerials[i.value.lot] = [];
                  }
            
                   dictSerials[i.value.lot][] = i.value.serial;
                }
            }
            

            上面的代码会将值添加到它们对应的键中。

            【讨论】:

            • 这是做什么的,它只添加了serialNumbers的最后一项。所以我添加了 2 批相同的不同序列号,只有一批“键”和一个序列“值”在 dictSerials 中。
            • 你能添加一些关于你的建议的描述吗?
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2013-10-20
            • 1970-01-01
            • 2023-03-12
            • 2017-11-01
            • 2010-10-04
            • 1970-01-01
            • 2016-08-02
            相关资源
            最近更新 更多