我正在过滤和映射数组对象,如下所示:
taxonomy:Object
data:Array[2]
0:Object
id:377
name:"Buss"
slug:"buss"
type:"post_tag"
1:Object
我的函数如下所示:
let tag = this.article.taxonomy.data.filter(function( data ) {
return data.type.includes('tag')
}).map(function(obj) {
return obj.name;
});
return tag;
我只是想知道有没有一种方法可以从 map 函数中获取字符串名称值,因为现在它返回["Buss"]
,这样就不需要使用函数末尾的索引:
return tag[0]
最佳答案
听起来你想要 find
,而不是过滤器
(如果您只查找一个结果)。 find
返回回调返回真值的第一个条目,如果从未返回过,则返回 undefined
。所以:
const obj = this.article.taxonomy.data.find(data => data.type.includes('tag'));
const tag = obj && obj.name; // Note the guard in case no entry matched
return tag; // Will be the name or `undefined`
(请注意,我假设您可以使用箭头函数,因为您正在使用 let
。如果没有,只需将其替换为 function
函数。)
实例:
const taxonomy = {
data: [
{
id: 375,
name: "A",
slug: "A",
type: "nope"
},
{
id: 376,
name: "B",
slug: "B",
type: "nor-this"
},
{
id: 377,
name: "Buss",
slug: "buss",
type: "post_tag"
},
{
id: 378,
name: "C",
slug: "C",
type: "blah"
}
]
};
const obj = taxonomy.data.find(data => data.type.includes('tag'));
const tag = obj && obj.name;
console.log(tag);
关于Javascript - 如何在过滤和映射对象数组后获取属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46034970/