繁体   English   中英

检测数组中的对象是否具有相同的属性,但其他属性与其他对象不同

[英]Detect if object in array has one same property but different other property to other objects

取这个数组:

[
  {"color": "blue","type": 1},
  {"color": "red","type": 1},
  {"color": "blue","type": 1},
  {"color": "green","type": 1},
  {"color": "green","type": 1},
  {"color": "red","type": 2},
  {"color": "red","type": 1},
  {"color": "green","type": 2},
  {"color": "red","type": 3},
];

我将如何查找数组中哪个“颜色”具有不同的“类型”(与所有其他具有相同“名称”的对象相比)?

我希望能够遍历此数组并创建另一个看起来像这样的数组:

{red, green}

请注意,由于所有具有“ color”:“ blue”的对象都具有相同的“ type”,因此省略了blue。

我得到的最接近的是: https : //jsfiddle.net/0wgjs5zh/,但是它将所有颜色添加到数组中并附加了不同的类型:

arr.forEach(function(item){
  if(newArr.hasOwnProperty(item.color+ '-' +item.type)) {
   // newArr[item.color+ '-' +item.type].push(item);
  }
  else {
    newArr[item.color+ '-' +item.type] = item;
  }
});

// RESULT
{blue-1, green-1, green-2, red-1, red-2, red-3}

您可以使用两次遍历,一次遍历集合,一次遍历生成结果数组。

 var array = [{ "color": "blue", "type": 1 }, { "color": "red", "type": 1 }, { "color": "blue", "type": 1 }, { "color": "green", "type": 1 }, { "color": "green", "type": 1 }, { "color": "red", "type": 2 }, { "color": "red", "type": 1 }, { "color": "green", "type": 2 }, { "color": "red", "type": 3 }, ], result, object = Object.create(null); array.forEach(function (a) { object[a.color] = object[a.color] || {}; object[a.color][a.type] = true; }); result = Object.keys(object).filter(function (k) { return Object.keys(object[k]).length > 1; }); console.log(result); 

我的解决方案如下

 var cls = [ {"color": "blue","type": 1}, {"color": "red","type": 1}, {"color": "blue","type": 1}, {"color": "green","type": 1}, {"color": "green","type": 1}, {"color": "red","type": 2}, {"color": "red","type": 1}, {"color": "green","type": 2}, {"color": "red","type": 3}, ], map = cls.reduce((p,c) => (p[c.color] ? !~p[c.color].indexOf(c.type) && p[c.color].push(c.type) : p[c.color] = [c.type], p),{}), result = Object.keys(map).reduce((p,c) => map[c].length > 1 && p.concat(c) || p,[]); console.log(result); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM