javascript 删除对象如果它的字段与其它数组不匹配

pbgvytdp  于 2023-01-01  发布在  Java
关注(0)|答案(2)|浏览(143)
let array = [
            {name: "60", origin: "tcs"},
            {name: "70", origin: "cfs"},
            {name: "80", origin: "ehg"},
    ]
undefined
let def = [
            {id: "60", testorigin: "tcs"},
            {id: null, testorigin: "cfs"},   // this line should be removed
            {id: "80", testorigin: "ehg"},
]

输出

[
    {name: "60", origin: "tcs"},
    {name: "80", origin: "ehg"},

]

我只想删除def的第二个元素,因为它的id为null,并且它与array的名称不匹配。
我试过很多方法,但都失败了,先谢谢你了。

dw1jzc5e

dw1jzc5e1#

这是解决方案。你只需要检查两个对象的条件相同的索引。这个答案会帮助你。

for(let i=0;i<array.length;i++){
    if(array[i].name == def[i].id){
        console.log(array[i])
    }
}

谢谢!

bejyjqdl

bejyjqdl2#

你可以这样做:

let array = [
  {name: "60", origin: "tcs"},
  {name: "70", origin: "cfs"},
  {name: "80", origin: "ehg"},
 ];
 
 let def = [
  {id: "60", testorigin: "tcs"},
  {id: null, testorigin: "cfs"},
  {id: "80", testorigin: "ehg"},
];

const result = array.filter(item => def.map(d => d.id).includes(item.name));
console.log('Result: ', result);

相关问题