删除javascript数组中的重复键值对

时间:2017-10-27 18:48:16

标签: javascript

我有一个以这种格式动态创建的javascript数组。

[{prdName: "Testing2"},
{prdName: "Testing2,Testing3"},
{markets: "Testing5"},
{markets: "Testing5,Testing6"}]

我想删除上面数组映射中的重复键并将其转换为此格式。

 [ {prdName: "Testing2,Testing3"},
   {markets: "Testing5,Testing6"} ]

你能告诉我如何实现这一目标吗?我正在研究reactjs应用程序。

3 个答案:

答案 0 :(得分:3)

使用ES6,您可以将MapSet用于唯一项目。



var array = [{ prdName: "Testing2" }, { prdName: "Testing2,Testing3" }, { markets: "Testing5" }, { markets: "Testing5,Testing6" }],
    map = new Map,
    result;

array.forEach(o => Object.keys(o).forEach(k => {
    if (!map.has(k)) {
        map.set(k, new Set);
    }
    o[k].split(',').forEach(s => map.get(k).add(s));
}));

result = [...map].map(([k, s]) => ({ [k]: [...s].join() }));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:2)

我假设您要保留所有非重复的逗号分隔条目,而不是像其他答案一样丢弃除最后一组之外的所有条目。 (例如,如果输入为[{foo: "x"}, {foo:"x,y"}, {foo:"z"}],则输出应为[{foo: "x,y,z"}],而不是[{foo:"z"}]。)

var rearrange = function(input) {
  var tmp = {}; // track keys and values as we find them
  for (obj of input) {
    var key = Object.keys(obj)[0]; // each input has one key
    tmp[key] = tmp[key] || {}; // initialize an empty object at that key in tmp if necessary
    var vals = obj[key].split(",");
    for (v of vals) {
      tmp[key][v.trim()] = 1; // keep each of the (trimmed) comma-delimited values, implicitly dropping duplicates
    }
  }

  // now convert the tmp object into an array:
  var output = [];
  for (k of Object.keys(tmp)) {
    var x = {};
    x[k] = Object.keys(tmp[k]).join(","); // merge the values back into a comma-separated string
    output.push(x);
  }
  return output;
}
console.log(rearrange([
  {prdName: "Testing2"},
  {prdName: "Testing2,Testing3"},
  {markets: "Testing5"},
  {markets: "Testing5,Testing6"}
]));

console.log(rearrange([
  {foo: "x"},
  {foo: "x,y"},
  {foo: "z"},
  {bar: "x,y,z"}
]));

但是,如果您需要的只是每个键的最后一个实例,那么这非常接近于单行;只需使用Object.assign合并对象:

var rearrange = function(input) {
   var merged = Object.assign({},...input); // merges all input keys, overwriting early values with later ones
   
   // convert to array (if necessary. the "merged" object might be easier to work with...):
   var output=[];
   for (k of Object.keys(merged)) {
     var x = {};
     x[k] = merged[k];
     output.push(x)
   }
   return output;
}

console.log(rearrange([
    {prdName: "Testing2"},
    {prdName: "Testing2,Testing3"},
    {markets: "Testing5"},
    {markets: "Testing5,Testing6"}
]));
     
console.log(rearrange([{foo: "x"}, {foo:"x,y"}, {foo:"z"}]));

答案 2 :(得分:1)



var lists =[{prdName: "Testing2"},

{prdName: "Testing2,Testing3"},

{markets: "Testing5"},

{markets: "Testing5,Testing6"}]

var newLists =[]
var keys = []
lists.forEach(item=>{
var key = Object.keys(item)[0];
if(keys.indexOf(key) === -1){
// first time the key is processed; it is stored in newLists
    keys.push(key);
    newLists.push(item);
  }
else {
// a duplicate key is found in the array
    let remove; 
    let values;
    newLists.forEach((item2,index) => {
        if (Object.keys(item2)[0] === key) {
// use of a set to have a union of values already stored for the key and the new values found for the same key using spread operator        
         values = new Set([...item2[key].split(","),...item[key].split(",")]);
            remove = index;
          }
    })
    newLists.splice(remove, 1);
    newLists.push({[key]:  Array.from(values).toString()})
  }
})

console.log(newLists);