【发布时间】:2022-01-04 20:11:47
【问题描述】:
我正在尝试使用字符串数组过滤对象数组,只返回字符串数组中具有相同namespace 的对象。
数组 1:
[
{
"pt-br": {
"title": "v2.pages.careers.title",
"og_image": "v2.pages.careers.og_image",
"url": "website.com",
"namespace": "careers"
},
"en": {
"title": "v2.pages.careers.title",
"og_image": "v2.pages.careers.og_image",
"url": "website.com",
"namespace": "careers"
},
"es": {
"title": "v2.pages.careers.title",
"og_image": "v2.pages.careers.og_image",
"url": "website.com",
"namespace": "careers"
}
},
{
"es": {
"title": "v2.pages.contact.title",
"og_image": "",
"url": "website.com",
"namespace": "contact"
}
},
{
"pt-br": {
"title": "pages.api_support.title",
"og_image": "",
"url": "website.com",
"namespace": "api_support"
},
"en": {
"title": "pages.api_support.title",
"og_image": "",
"url": "website.com",
"namespace": "api_support"
}
},
{
"pt-br": {
"title": "pages.api.title",
"og_image": "",
"url": "website.com",
"namespace": "api"
},
"en": {
"title": "pages.api.title",
"og_image": "",
"url": "website.com",
"namespace": "api"
}
},
{
"pt-br": {
"title": "pages.code_of_ethics.title",
"og_image": "",
"url": "website.com",
"namespace": "documentation_other_documents_code_of_ethics"
},
"en": {
"title": "pages.code_of_ethics.title",
"og_image": "",
"url": "website.com",
"namespace": "documentation_other_documents_code_of_ethics"
}
}
]
数组 2:
["api_support", "careers"]
新数组应仅返回数组 2 中 namespace 字段等于 1 的四个项目。
如您所见,Array 1 对象的每个项目都具有三种不同的语言:es、pt-br 和 en。根据“语言”变量下的预定义语言进行过滤也很重要。在这种情况下,它应该只返回 pt-br 项。
到目前为止我已经尝试过:
const myArrayFiltered = arrayOne.filter((el) => {
return arrayTwo.some((id) => {
console.log(el[lang].namespace != undefined && el[lang].namespace === id)
return el[lang].namespace != undefined && el[lang].namespace === id
});
});
返回是TypeError: Cannot read properties of undefined (reading 'namespace')。我可以看到它的发生是因为有些对象并非在所有语言中都可用。
有办法解决吗?
【问题讨论】:
-
你从哪里得到
lang?请将代码添加到 stacksn-ps 中。 -
数组中的第二个元素没有
pt-br属性,因此el[lang]返回未定义,然后您尝试读取namespace。您的预期输出是什么? -
const myArrayFiltered = arrayOne.filter((el) => el[lang] && arrayTwo.includes(el[lang]?.namespace)); -
你写“新数组应该只返回数组 2 中命名空间字段等于一个的四个项目”,但根据你的描述,它应该只返回两个项目/对象
标签: javascript arrays filter