如何組合兩個數組(配置文件和國家/地區),但過濾兩個數組中名稱相同的任何對象(但只刪除具有 IsDirector: null 的對象)
我猜它是 concat 和 filter 的組合,但不確定如何讓它工作。
數據:
let profile = [
{
"IsDirector":true,
"Name":"Germany"
},
{
"IsDirector":false,
"Name":"Spain"
},
]
let countries = [
{
"IsDirector":null,
"Name":"Germany"
},
{
"IsDirector":null,
"Name":"Spain"
},
{
"IsDirector":null,
"Name":"Portugal"
}
]
想要的結果:
[
{
"IsDirector":true,
"Name":"Germany"
},
{
"IsDirector":false,
"Name":"Spain"
},
{
"IsDirector":null,
"Name":"Portugal"
}
]
將第一個數組轉換為對像以便更好地訪問和使用 map
const profile = [
{
"IsDirector":true,
"Name":"Germany"
},
{
"IsDirector":false,
"Name":"Spain"
},
]
const countries = [
{
"IsDirector":null,
"Name":"Germany"
},
{
"IsDirector":null,
"Name":"Spain"
},
{
"IsDirector":null,
"Name":"Portugal"
}
]
function f() {
const p = Object.fromEntries(profile.map(el => ([el.Name, el])));
return countries.map(el => ({ ...el, IsDirector: p[el.Name]?.IsDirector ?? null }));
}
console.log(f());
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句