【发布时间】:2019-03-29 16:43:47
【问题描述】:
我正在尝试构建一个数据结构,其中所有元素都将根据对象键进行分组。
一切正常,除了我无法检查新数组是否有重复的数据,因为它在for..of 循环之外。我正在寻找一种方法来防止push在新数组已经拥有另一个对象的情况下使用它。
当前输出(注意来自日本的字符列表出现了两次)
[
[
{ "country": "US" },
[
{ "name": "Guile", "country": "US" }
]
],
[
{ "country": "Japan" },
[
{ "name": "E. Honda", "country": "Japan" },
{ "name": "Ryu", "country": "Japan" }
]
],
[
{ "country": "Japan" },
[
{ "name": "E. Honda", "country": "Japan" },
{ "name": "Ryu", "country": "Japan" }
]
],
[
{ "country": "Thailand" },
[
{ "name": "Sagat", "country": "Thailand" }
]
]
]
预期输出
[
[
{ "country": "US" },
[
{ "name": "Guile", "country": "US" }
]
],
[
{ "country": "Japan" },
[
{ "name": "E. Honda", "country": "Japan" },
{ "name": "Ryu", "country": "Japan" }
]
],
[
{ "country": "Thailand" },
[
{ "name": "Sagat", "country": "Thailand" }
]
]
]
我目前所拥有的
var data = [
{name: 'Guile', country: 'US'},
{name: 'E. Honda', country: 'Japan'},
{name: 'Ryu', country: 'Japan'},
{name: 'Sagat', country: 'Thailand'}
]
const getNationList = (streetFighterList) => {
let filteredList = []
for (const [index, characterData] of streetFighterList.entries()) {
// .......................................................
// looking for ways here to check if `filteredList` already
// has the data I'm trying to push. Since it's empty
// I don't know how to check its index. :(
// NOTE: indexOf() doesn't seem to work
// .......................................................
const indexOf = filteredList.indexOf(streetFighterList[index].country)
if (indexOf == -1) {
filteredList.push([
{ country: characterData.country },
streetFighterList.filter((character) => {
return character.country === characterData.country
})
])
}
}
return filteredList
}
console.log(getNationList(data))
注意:我知道,鉴于 country 对象始终是唯一的,如果我改用字符串,这个数据结构会更好、更容易。然而,这是一个示例数据,在现实生活中的代码中,我确实需要将它存储为一个对象。
【问题讨论】:
-
是否可以将您的对象格式更改为 { [country]: [names] }?那么更容易删除重复并找到属于同一国家/地区的名称
-
很遗憾没有。我需要 obj 键是不可变的
标签: javascript arrays loops for-loop