如果存在于另一个数组中

如果存在于另一个数组中

本文介绍了根据值从一个数组中删除对象(如果存在于另一个数组中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最后一个问题没有得到很好的答复,可能是重复的问题.再次写信解释这有点不同,因为无法获得我想要的解决方案.

Last question did not get well received as was a possible duplicate. Writing again to explain how this is slightly different as can't get the solution I want.

我有一个名为 _USERS 的数组和另一个名为 newArray 的数组.

I have an array called _USERS and another one called newArray.

newArray看起来像这样:

newArray looks like this:

newArray = ["BLRlXKIeWkanHiSCXbBCFRTIaqk1", "sF4gWbZvAMPmrbeHsKzln7LowOx2"]

_USERS 是对象的数组,并且这些对象具有名为 useruid 的属性/属性,该属性/属性等于字符串.如果 useruid 字符串与newArray中找到的任何字符串匹配,如何从 _USERS 中删除对象.

_USERS is an array of objects and the objects have a property/attribute called useruid which equals a string. How can I remove an object from _USERS if the useruid string matches ANY string found in the newArray.

我尝试过的解决方案包括:

Solutions I have tried include:

for (var k = 0; k < newArray.length; k++){
        if (_USERS[j].useruid == newArray[k]){
          _USERS.splice(newArray[k])
        }

var result = _.differenceWith(_USERS, newArray, _.isEqual);

这些都不起作用,我只是不能完全把手指放在丢失的部分上

neither of these have worked and I just cant quite put my finger on the missing piece

初始_用户代码:

console.log(_USERS) => [Object, Object, Object, Object]

每个对象都有

gender: "male", name: "Rich", username: "[email protected]", useruid: "BLRlXKIeWkanHiSCXbBCFRTIaqk1"

newArray = ["BLRlXKIeWkanHiSCXbBCFRTIaqk1","sF4gWbZvAMPmrbeHsKzln7LowOx2"]

newArray [0] =一个字符串.该字符串与 Rich 对象中的useruid匹配.因此,我希望将其删除,然后进行以下操作

newArray[0] = a string. This string matches the useruid in the Rich object. therefore I would like that to be deleted and then the below to happen

console.log(_USERS) => [Object, Object, Object]

推荐答案

对我来说,这似乎是一个简单的过滤器:

It looks like a simple filter to me:

let filteredUsers = _USERS.filter(u => !newArray.includes(u.useruid))

这里正在起作用:

var newArray = ["BLRlXKIeWkanHiSCXbBCFRTIaqk1", "sF4gWbZvAMPmrbeHsKzln7LowOx2"]

var _USERS = [{ gender: "male", name: "Rich", username: "[email protected]", useruid: "BLRlXKIeWkanHiSCXbBCFRTIaqk1" }]

let filteredUsers = _USERS.filter(u => !newArray.includes(u.useruid));

/*Printing*/
/*Before*/
document.write("Before: <br>" + JSON.stringify(_USERS) + "<br><br>");
/*After*/
document.write("After <br>" + JSON.stringify(filteredUsers));

这篇关于根据值从一个数组中删除对象(如果存在于另一个数组中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 13:33