This question already has answers here:
JavaScript get elements from an object array that are not in another
                                
                                    (5个答案)
                                
                        
                                5个月前关闭。
            
                    
我想要一个数组,其中包含scrape对象中不包含在old对象中的对象。我实际使用的数组包含近100个对象。

下面的代码有效,但是我想知道是否有更有效的方法来获得相同的结果?

var old = [
  {a: 6, b: 3},
  {a: 1, b: 1},
  {a: 3, b: 3}
]

var scrape = [
  {a: 1, b: 1},
  {a: 5, b:5}
]

var nogood = []
var good =[]

scrape.forEach(es => {
  old.forEach(e => {
    if(e.a == es.a) {
      nogood.push(es)
    }
  })
})
console.log(nogood)

nogood.forEach(main =>
  good = scrape.filter(e=> e.a!=main.a)
)
console.log(good)


这是我的期望以及得到的:

good = {a:5, b:5}

最佳答案

我个人将使用以下方法:

const old = [
  {a: 6, b: 3},
  {a: 1, b: 1},
  {a: 3, b: 3}
];

const scrape = [{a: 1, b: 1}, {a: 5, b:5}];

for (const item of old) {
  for (const i in scrape) {
    if (JSON.stringify(item) === JSON.stringify(scrape[i])) {
      scrape.splice(i, 1); //delete the previously scraped item
    }
  }
}

console.log(scrape); //{a: 5, b:5}


这种方法的好处是:


您不在乎所比较的对象具有哪些属性,
   您只关心它们是否相同。
它很快
   (比较JSON通常比遍历对象更快
   比较每个属性)。
拼接刮板更加简洁
   数组,而不是添加“好”和“不好”的数组
   过滤后的抓取数组。


如果您要比较的对象包含方法,那么可能会破坏交易,在这种情况下,通过JSON比较它们不是正确的方法。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

关于javascript - 如何从一个数组中未包含在第二个数组中的对象中最好地创建对象数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56941409/

10-11 23:03
查看更多