我想在网站上搜索“搜索”的每个国家/地区的JSON数据属性名称
let array = {
continents: [
{
name: "Europe",
countries: [
{
name: "Austria",
adresses: {
1: "one",
2: "two",
3: "three"
}
},
{
name: "Germany",
adresses: {
1: "one",
2: "two",
3: "three"
}
}
]
},
{
name: "Asia",
countries: [
{
name: "Thailand",
adresses: {
1: "one",
2: "two",
3: "three"
}
},
{
name: "Japan",
adresses: {
1: "one",
2: "two",
3: "three"
}
}
]
}
]
};
预期的行为是当我输入“an”时结果将是一个类似的数组:
let array = {
continents: [
{
name: "Europe",
countries: [
{
name: "Germany",
adresses: {
1: "one",
2: "two",
3: "three"
}
}
]
},
{
name: "Asia",
countries: [
{
name: "Thailand",
adresses: {
1: "one",
2: "two",
3: "three"
}
},
{
name: "Japan",
adresses: {
1: "one",
2: "two",
3: "three"
}
}
]
}
]
};
所以我们将摆脱奥地利
如何实现这一目标?我们应该使用fliter函数(基准测试显示它很慢,基于:https://jsperf.com/function-loops/11)。我们也可以在大陆名称
中搜索现在我知道如何记录正确的值,但是如何从中组合正确的数组?
let array = {
continents: [
{
name: "Europe",
countries: [
{
name: "Austria",
adresses: {
1: "one",
2: "two",
3: "three"
}
},
{
name: "Germany",
adresses: {
1: "one",
2: "two",
3: "three"
}
}
]
},
{
name: "Asia",
countries: [
{
name: "Thailand",
adresses: {
1: "one",
2: "two",
3: "three"
}
},
{
name: "Japan",
adresses: {
1: "one",
2: "two",
3: "three"
}
}
]
}
]
};
searchValue = "an";
for (let i = 0; i < array.continents.length; i++) {
for (let j = 0; j < array.continents[i].countries.length; j++) {
if (
array.continents[i].countries[j].name
.toLowerCase()
.includes(searchValue.toLowerCase())
) {
console.log(array.continents[i].countries[j].name);
}
}
}
答案 0 :(得分:0)
嗯..创建一个空数组,并在符合搜索条件时推送国家名称:
const array = {
continents: [{
name: "Europe",
countries: [{
name: "Austria",
adresses: {
1: "one",
2: "two",
3: "three"
}
},
{
name: "Germany",
adresses: {
1: "one",
2: "two",
3: "three"
}
}
]
},
{
name: "Asia",
countries: [{
name: "Thailand",
adresses: {
1: "one",
2: "two",
3: "three"
}
},
{
name: "Japan",
adresses: {
1: "one",
2: "two",
3: "three"
}
}
]
}
]
}
const searchValue = "an"
let result = []
array.continents.forEach(e =>
e.countries.forEach(v =>
v.name.toLowerCase().includes(searchValue) && result.push(v.name))
)
console.log(result)
&#13;