【问题标题】:How to filter JSON values based on key values and remove the duplicate values如何根据键值过滤 JSON 值并删除重复值
【发布时间】:2021-12-05 08:27:30
【问题描述】:

我有以下 Json

var initialdata = [
{
  "type": "Feature",
  "properties": {
    "Region": "US",
    "SubRegion": "US-1",
    "SiteID": "234"
  },
  "geometry": {
    "type": "Point"
  }
},
{
  "type": "Feature",
  "properties": {
    "Region": "US",
    "SubRegion": "US-1",
    "SiteID": "235"
  },
  "geometry": {
    "type": "Point"
  }
},
{
  "type": "Feature",
  "properties": {
    "Region": "US",
    "SubRegion": "US-2",
    "SiteID": "234"
  },
  "geometry": {
    "type": "Point"
  }
},
{
  "type": "Feature",
  "properties": {
    "Region": "UK",
    "SubRegion": "UKK",
    "SiteID": "121"
  },
  "geometry": {
    "type": "Point"
  }
},
{
  "type": "Feature",
  "properties": {
    "Region": "UK",
    "SubRegion": "UKK",
    "SiteID": "121"
  },
  "geometry": {
    "type": "Point"
  }
}
]

我有基于 initialdata.properties 键的下拉菜单 例如,我有如下下拉菜单

Region
SubRegion
SiteID

如果用户选择 Region 下拉意味着,我需要以下输出作为用户选择列表,不重复

US
UK

我怎样才能做到这一点?

如果有人有任何想法,请与我分享

【问题讨论】:

    标签: arrays reactjs json sorting filter


    【解决方案1】:

    您可以使用一个函数将其简化为一个可用于下拉列表的数组。

    initialData.reduce((prev, cur) => {
         if(!prev.includes(cur.properties.Region)) {
            prev.push(cur.properties.Region)      
    }
    return prev
    }, [])
    

    如果您需要属性中的另一个键而不是 region,您可以将该值存储在 a const 中并在 reduce 函数中使用它。 例如:cur.properties[dropdownSelected]

    【讨论】:

    • 感谢您的回复,但它会抛出一些未定义的包含错误。你能根据我的代码给我一个示例吗?
    • 请检查上面的代码,我已经编辑了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    相关资源
    最近更新 更多