我有一个 React 组件,我在其中使用字典来与地址状态的 API 响应进行比较,并仅映射作为下拉列表中的选项返回的状态。
这是我用来创建返回状态数组的映射函数:
let activeStates = props.locations.map(x => ({abbr: x.address.state, name: states[x.address.state]as string}));
对照我的字典,看起来像这样:
const states = {
AL: "Alabama",
AK: "Alaska",
AZ: "Arizona",
AR: "Arkansas",
CA: "California",
CO: "Colorado",
(all US states are included)
};
这会在响应中创建一个包含所有位置地址的数组,如下所示:
3:
abbr: "3"
name: {abbr: "TN", name: "Tennessee"}
__proto__: Object
4:
abbr: "4"
name: {abbr: "WI", name: "Wisconsin"}
__proto__: Object
5:
abbr: "5"
name: {abbr: "NC", name: "North Carolina"}
__proto__: Object
6:
abbr: "6"
name: {abbr: "NC", name: "North Carolina"}
这为我的组件提供了数据,我将数组映射到下拉列表:
<select value={state} onChange={handleStateChange}>
<option value={''}>All</option>
{activeStates.map((state) => (
<option value={state.abbr}>{state.name}</option>))}
</select>
我正在尝试编写一个基于 activeStates
工作的函数,以创建一个仅包含每个状态/缩写之一的新数组,而不是生成重复项。我知道,因为该映射数组中返回的所有值都被认为是唯一的,所以我需要运行索引函数来消除重复项,但我不确定如何操作。
到目前为止我用过:
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 }));
let activeStates = props.locations.map(x => ({abbr: x.address.state, name: states[x.address.state]}));
let uniqueStates = new Set(activeStates);
let uniqueStatesArray = [...uniqueStates]
和
let activeStates = Array.from(new Set(props.locations.map(x => ({ abbr: x.address.state, name: states[x.address.state]})))
这些都不起作用。
最佳答案
你走在正确的道路上。
将对象添加到 Set 时是通过引用:
const s = new Set()
const o = { a: 1, b: 2 }
s.add(o)
console.log(s.has(o)) // true
console.log(s.has({ a: 1, b: 2 })) // false
这可能会导致您可能无法预料的其他影响:
const s = new Set()
s.add({ a: 1, b: 2 })
s.add({ a: 1, b: 2 })
s.add({ a: 1, b: 2 })
console.log(s) // Set { { a: 1, b: 2 }, { a: 1, b: 2 }, { a: 1, b: 2 } }
要回答您的问题,您可以使用对象的一个属性将其添加到用于检查的集合中:
const dropDuplicates = arr => {
const seen = new Set()
const result = []
for (let obj of arr) {
if (!seen.has(obj.abbr)) { // check if `abbr` has been seen
result.push(obj) // if not, then add state to result
seen.add(obj.abbr) // this state is now seen, don't add anymore
}
}
return result
}
关于javascript - 使用字典映射 API 响应并创建对象数组,尝试删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60117052/