简体   繁体   English

如何在 React js 中创建 json object 文字的唯一数据集?

[英]How do I create an unique dataset of json object literal in React js?

I want to get an output as an unique set of Categories array with the following output [Men,Woman].我想获得一个 output 作为一组独特的类别数组,其中包含以下 output [Men,Woman]。 Is there any way to do it in React?有什么办法可以在 React 中做到这一点?

For example this my data例如这是我的数据

{
  "products:"[
    {
      "id": 1,
      "categories": {
        "1": "Men",
      },
    },
    {
      "id": 2,
      "categories": {
        "1": "Men",
      },
    }, {
      "id": 3,
      "categories": {
        "1": "Woman",
      },
    }
  ];
}

A simple 1 line answer would be一个简单的 1 行答案是

new Set(input.products.map(p => p.categories["1"]))

This is if you're expecting only key "1" in the categories object.这是如果您只希望类别 object 中的键“1”。

If it can have multiple categories then you can always do如果它可以有多个类别,那么你总是可以这样做

const uniqueCategories = new Set();

input.products.forEach(p => uniqueCategories.add(...Object.values(p.categories)))

Now you can convert a Set into an array现在您可以将 Set 转换为数组

PS: This is not a ReactJs problem but a pure JS question. PS:这不是 ReactJs 问题,而是纯 JS 问题。 You might want to remove the ReactJs tag from this question altogether.您可能希望完全从此问题中删除 ReactJs 标记。

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

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