我正在尝试根据该对象属性值检索对象数组中的对象。这是我的阵列:
const address_components = [
{
long_name: "11237",
short_name: "11237",
types: ["postal_code"]
},
{
long_name: "Kings County",
short_name: "Kings County",
types: ["political, administrative_area_level_2"]
},
{
long_name: "New York",
short_name: "NY",
types: ["political", "administrative_area_level_1"]
},
{
long_name: "United States",
short_name: "US",
types: ["political", "country"]
}
];
我想检索包含" country"的对象在types
属性中。我试着做了
var result = address_components.filter( obj => {
return obj.types === "country";
});
console.log(result);
// logs undefined
控制台记录undefined
。但是,当我使用另一个属性尝试此过滤器方法时,我得到了该对象。
var result = address_components.filter( obj => {
return obj.short_name === "US";
});
console.log(result);
// logs object
有谁知道如何根据types
属性中的项目过滤数组?
答案 0 :(得分:3)
type
是一个数组,您可以使用includes
检查数组是否包含字符串。
const address_components = [{
long_name: "11237",
short_name: "11237",
types: ["postal_code"]
},
{
long_name: "Kings County",
short_name: "Kings County",
types: ["political", "administrative_area_level_2"]
},
{
long_name: "New York",
short_name: "NY",
types: ["political", "administrative_area_level_1"]
},
{
long_name: "United States",
short_name: "US",
types: ["political", "country"]
}
];
var result = address_components.filter(obj => {
return obj.types.includes("country");
});
console.log(result);
使用多个搜索参数,您可以使用some()
const address_components = [{long_name: "11237",short_name: "11237",types: ["postal_code"]}, {long_name: "Kings County",short_name: "Kings County",types: ["political", "administrative_area_level_2"]},{long_name: "New York",short_name: "NY",types: ["political", "administrative_area_level_1"]},{long_name: "United States",short_name: "US",types: ["political", "country"]}];
var result = address_components.filter(obj => {
return obj.types.some(o => ['country', 'postal_code'].includes(o));
});
console.log(result);
Doc:includes()
答案 1 :(得分:2)
属性.short_name
是一个字符串,而types
是一个数组。检查等效性(==
)适用于字符串,但您需要检查数组的成员资格。
此外,如果你的箭头函数很简单,你可以省略大括号:
let result = address_components.filter(obj => obj.types.includes('country'))
答案 2 :(得分:0)
由于types
是一个数组,因此您应该使用indexOf
方法。
indexOf()方法返回调用String中的索引 第一次出现指定值的对象,开始 在fromIndex搜索。如果找不到值,则返回-1。
indexOf
优于includes
的优点是旧版浏览器支持indexOf
而includes
不支持。{/ p>
const address_components = [{
long_name: "11237",
short_name: "11237",
types: ["postal_code"]
},
{
long_name: "Kings County",
short_name: "Kings County",
types: ["political, administrative_area_level_2"]
},
{
long_name: "New York",
short_name: "NY",
types: ["political", "administrative_area_level_1"]
},
{
long_name: "United States",
short_name: "US",
types: ["political", "country"]
}
];
var result = address_components.filter(obj => {
return obj.types.indexOf("country") > -1;
});
console.log(result);
答案 3 :(得分:0)
这里使用不同的方法http://jsben.ch/jmHQg
进行不同的表演最快的是使用.filter()
和.includes()
有趣的是.map()
和.includes()
表现最差,至少在此实施中是这样的:
var result = [];
address_components.map(obj => {
if(obj.types.includes("country")){
result.push(obj);
}
});
console.log(result);