简体   繁体   English

使用字典将返回的状态映射到选择下拉列表以进行过滤,产生重复项,我试图删除这些重复项并将唯一键附加到

[英]Using dictionary to map returned states to a select dropdown for filtering, produces duplicates that I'm trying to remove and attach a unique key to

I have a dictionary object in a React component that I'm using to compare against an API response and then map only the address states that are returned.我在 React 组件中有一个字典对象,我用它来与 API 响应进行比较,然后只映射返回的地址状态。

The mapped address states are then used to dynamically populate the options on the <select> dropdown used for filtering locations 'by state'.然后使用映射的地址状态动态填充<select>下拉列表中的选项,用于“按状态”过滤位置。

I have a separate function call out to the parent container component of my filter component that loads all the filters and updates depending on a dropdown selection.我有一个单独的函数调用我的过滤器组件的父容器组件,它根据下拉选择加载所有过滤器和更新。 I've included that in as well for context.我也将其包含在上下文中。

The problem I'm running into is that certain responses contain multiple locations that contain the same address state.我遇到的问题是某些响应包含多个包含相同地址状态的位置。

Right now I'm using the state abbreviation as the unique key but obviously that doesn't work for duplicates.现在我使用州缩写作为唯一键,但显然这不适用于重复项。

I've tried using Set and Array.from but so far no dice.我试过使用SetArray.from但到目前为止没有骰子。

My attempted functions are below as well as the component itself.我尝试的功能如下以及组件本身。 Any ideas are hugely appreciated!任何想法都非常感谢!

Current Component:当前组件:

export const LocationFilterSection = (props: Props) => {
  const [state, setState] = useState<string>('');

  const handleStateChange = e => {
    setState(e.target.value);
    props.onFilterChange(statuses, state)
  };

  let statesObj = props.locations.reduce((acc, curr) => {
    acc[curr.address.state] = states[curr.address.state];
    return acc;
 }, {});


   let uniqueStates = Object.entries(statesObj).map(([abbr, name]) => ({abbr, name }));

return (
    <FilterContainer>
      <Container fluid={true}>
        <Row>
          <Col>
            <div>FILTER BY STATE</div>
            <select value={state} onChange={handleStateChange}>
            <option value={''}>All</option>
              {uniqueStates.map((state) => (
                <option value={state.abbr} key={state.abbr}>{state.name}</option>
              ))}
            </select>
          </Col>
        </Row>
      </Container>
    </FilterContainer>
  );
};

Attempted methods using Set and Array.from :尝试使用SetArray.from方法:

This comes back with an error on the last line saying: Type 'Set<{ abbr: string;这在最后一行返回一个错误,说: Type 'Set<{ abbr: string; name: any;名称:任何; }>' is not an array type or a string type. }>' 不是数组类型或字符串类型。

  let activeStates = props.locations.map(x => ({abbr: x.address.state, name: states[x.address.state]}));
  let uniqueStates = new Set(activeStates);
  let uniqueStatesArray = [...uniqueStates]

And this throws an error Encountered two children with the same key:这会引发错误遇到两个具有相同密钥的孩子:

let activeStates = Array.from(new Set(props.locations.map(x => ({ abbr: x.address.state, name: states[x.address.state]}))))

Dictionary of States I'm using to map against:我用来映射的状态字典:

const states = {
  AL: "Alabama",
  AK: "Alaska",
  AZ: "Arizona",
  AR: "Arkansas",
  CA: "California",
  CO: "Colorado",
  CT: "Connecticut",
  DE: "Delaware",
  FL: "Florida",
  GA: "Georgia",
  HI: "Hawaii",
  ID: "Idaho",
  IL: "Illinois",
  IN: "Indiana",
  IA: "Iowa",
  KS: "Kansas",
  KY: "Kentucky",
  LA: "Louisiana",
  ME: "Maine",
  MD: "Maryland",
  MA: "Massachusetts",
  MI: "Michigan",
  MN: "Minnesota",
  MS: "Mississippi",
  MO: "Missouri",
  MT: "Montana",
  NE: "Nebraska",
  NV: "Nevada",
  NH: "New Hampshire",
  NJ: "New Jersey",
  NM: "New Mexico",
  NY: "New York",
  NC: "North Carolina",
  ND: "North Dakota",
  OH: "Ohio",
  OK: "Oklahoma",
  OR: "Oregon",
  PW: "Palau",
  PA: "Pennsylvania",
  RI: "Rhode Island",
  SC: "South Carolina",
  SD: "South Dakota",
  TN: "Tennessee",
  TX: "Texas",
  UT: "Utah",
  VT: "Vermont",
  VA: "Virginia",
  WA: "Washington",
  WV: "West Virginia",
  WI: "Wisconsin",
  WY: "Wyoming"
};

Set() can't determine unique items if some nested property is same.如果某些嵌套属性相同,则Set()无法确定唯一项。 You first need to get a set of unique string values and then map those values to your objects.您首先需要获取一组唯一的字符串值,然后将这些值映射到您的对象。 You can also achieve this by creating an object with abbr as keys and name as values and then create an array from that object您还可以通过创建一个以abbr作为键和name作为值的对象,然后从该对象创建一个数组来实现这一点

 let statesObj = props.locations.reduce((acc, curr) => { acc[curr.address.state] = states[curr.address.state]; return acc; }, {}); let uniqueStates = Object.entries(statesObj).map(([abbr, name]) => ({abbr, name }));

Are there other fields within your state object that you could concatenate to create a unique key?您的state对象中是否还有其他字段可以连接以创建唯一键? For instance, will this combination of name and abbr be unique?例如, nameabbr这种组合是否是唯一的?

key={`${state.abbr},${state.name}`}

暂无
暂无

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

相关问题 使用字典映射 API 响应并创建对象数组,尝试删除重复项 - Using dictionary to map against an API response and create array of objects, trying to remove duplicates 我正在尝试基于更改选择器使用on()附加事件 - I'm trying to attach events using on() based on changing selectors 在 DropDown select 中映射出独特的结果 - Map out unique results in DropDown select 我正在尝试使用$ .map将值放入新数组,但无法正常工作 - Using $.map i'm trying to put values into new array but is not working 我正在尝试将状态发送给父母组件。 但是不明白 - I'm trying to send the states to the parents components. But do not get it 基本天气应用:我正在尝试根据用户在下拉菜单中选择的城市来更改向用户显示的内容 - Basic Weather app: I'm trying to change what is displayed to the user based on what city they select on a dropdown HTML使用(countries.js)选择下拉列表的国家和地区 - HTML select dropdown countries and states using (countries.js) 使用多重选择下拉菜单从国家表中选择国家时,如何从状态表中获得国家状态列表? - how can i get countries states list from states table ,when i select country from countries table using multiple selection dropdown? 使用AngularJS指令从select中删除重复项 - Remove duplicates from select using AngularJS directive 尝试制作地图时,为什么会收到独特的“钥匙”警告? - Why am I getting a unique “key” warning when trying to do a map?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM