嵌套数组响应图上的IndexOf只返回[]



我正试图通过articleTag从graphql响应中筛选一些文章。我的结构如下:

{
"id": "41744081",
"articleTitle": "text",
"articleContent": "text",
"categoryName": { "categoryName": "Company", "id": "38775744" },
"articleTags": [
{ "articleTag": "event", "id": "37056861" },
{ "articleTag": "car", "id": "37052481" },
]
},
{
"id": "41754317",
"articleTitle": "text",
"articleContent": "text",
"categoryName": { "categoryName": "Sales and Martketing", "id": "38775763" },
"articleTags": [{ "articleTag": "technology", "id": "37056753" }]
},
...

但在应用我的函数时:

notificationFiltered () {
var articleResponse = this.response.allArticles;
var routeParam =  this.$route.params.tagName; //contains the id of the tag

const filteredTag = articleResponse.filter((item) => {
return (item.articleTags.indexOf(routeParam) >= 0);
});
console.log(filteredTag);
},

当我";console.log";结果我只得到一个";[]";。不确定是否与正在呈现的查询方式有关,在API中,我得到了相同的格式,但略有不同的

{
"data": {
"allArticles": [... the specify structure above]  
}
}

在使用vue{{response.allArticles}}打印时,我只得到了第一个结构,我认为这应该无关紧要吗?

提前感谢的建议

您将无法使用对象数组的indexOf来找到匹配的对象-只需要严格的等式,这在参考域中很难获得。考虑一下:

const objs = [
{ foo: 'bar' }, 
{ foo: 'baz' }, 
{ foo: 'foo' } // whatever
];
const needle = { foo: 'baz' };
objs.indexOf(needle);
// -1

什么?是的,该数组中有一个看起来与needle完全相似的对象,但它是一个不同的对象:

objs[1] === needle; // false

这就是为什么indexOf刚好超过这个值,并给出-1,a";未找到";后果

在这种情况下,您应该能够使用findIndex。仍然需要构建谓词才能进行匹配。例如:

const objs = [
{ foo: 'bar' }, 
{ foo: 'baz' }, 
{ foo: 'foo' }
];
const needle = { foo: 'baz' };
objs.findIndex(el => JSON.stringify(el) === JSON.stringify(needle)); 
// 1

在这个例子中,在谓词函数中比较JSON.stringify的结果是一个穷人的_.isEqual——只是为了说明这个概念。您应该考虑在代码中实际使用_.isEqual本身,或者您选择的工具箱中提供的类似函数。

或者,您可以只检查特定字段的值:

objs.findIndex(el => el.foo === needle.foo); // still 1

这显然会找到对象,即使它们的其他属性不匹配。

最新更新