首页 > 解决方案 > 遍历列表中的对象并返回唯一值

问题描述

我正在寻找一种有效的方法来返回数组内对象中的唯一值。例如下一个对象:

{
    "products": [{
        "id": 1, 
        "category": "test1",
        "tags": {
            "option": ["A", "B"]
        }
    }, {
        "id": 2,
        "category": "test2",
        "tags": {
            "option": ["B"],
            "type": ["A", "B", "C"]
        }
    }, {
        "id": 3,
        "category": "test1",
        "tags": {
            "type": ["A"]
        }
    }, {
        "id": 4,
        "category": "test2",
        "tags": {
            "option": ["B", "C"],
            "type": ["A", "C"]
        }
    }]
}

我要返回的是以下内容:

{"option": [ "A", "B", "C" ] },{"type": ["A", "B", "C"] }

所以我想为标签对象内的每个项目创建一个新对象。之后,我想要一个包含所有产品的所有唯一值的数组。

我对另一个功能做了一些相同的事情:

Array.from(new Set(data.map(p => { return p.category; })))

这是一个更高的级别,这使得它更容易。有人可以将我推向正确的方向吗?

标签: javascriptarrays

解决方案


改为制作两组,一组用于目前option找到的 s,一组用于目前找到的types:

const obj = {
  "products": [{
    "id": 1,
    "tags": {
      "option": ["A", "B"]
    }
  }, {
    "id": 2,
    "tags": {
      "option": ["B"],
      "type": ["A", "B", "C"]
    }
  }, {
    "id": 3,
    "tags": {
      "type": ["A"]
    }
  }, {
    "id": 4,
    "tags": {
      "option": ["B", "C"],
      "type": ["A", "C"]
    }
  }]
};
const options = new Set();
const types = new Set();
for (const { tags: { option=[], type=[] } } of obj.products) {
  for (const o of option) options.add(o);
  for (const t of type) types.add(t);
}
console.log({
  option: [...options],
  type: [...types]
});

对于任意键,另一种选择:

const obj = {
  "products": [{
    "id": 1,
    "tags": {
      "option": ["A", "B"]
    }
  }, {
    "id": 2,
    "tags": {
      "option": ["B"],
      "type": ["A", "B", "C"]
    }
  }, {
    "id": 3,
    "tags": {
      "type": ["A"]
    }
  }, {
    "id": 4,
    "tags": {
      "option": ["B", "C"],
      "type": ["A", "C"]
    }
  }]
};
const setObj = {};
for (const { tags } of obj.products) {
  for (const [key, arr] of Object.entries(tags)) {
    if (!setObj[key]) setObj[key] = new Set();
    for (const item of arr) setObj[key].add(item);
  }
}
const output = Object.fromEntries(
  Object.entries(setObj).map(([key, set]) => [key, [...set]])
);
console.log(output);


推荐阅读