简体   繁体   中英

Check if an object exists in other objects' sub-objects within an array

I have kind of this Array :

array = [
     {
      a:0, 
      b:{x:1,y:2} 
     },
     {
      c:0,
      b:{x:3,y:2}},
    ]

And I have a new object like this

{
 e:0, 
 b:{x:2,y:5}
}

I want to test whether the objects in array have the same nested b object or not, if so I'll push the new object there, if it already exists, I'll replace the whole object with the newer one. Any help how could I achieve that please (Lodash, ES6..), I'm using Typescript btw.

You can simply use Array.prototype.some() method with your array to test if there's any matching b object with the searched object, your code will be:

function checkIfObjectExists(array, obj) {
  return array.some(function(element) {
    return (typeof obj.b === typeof element.b) && JSON.stringify(obj.b) === JSON.stringify(element.b);
  });
}

This is a working snippet:

 function checkIfObjectExists(array, obj) { return array.some(function(element) { return (typeof obj.b === typeof element.b) && JSON.stringify(obj.b) === JSON.stringify(element.b); }); } array = [{ a: 0, b: { x: 1, y: 2 } }, { c: 0, b: { x: 3, y: 2 } }, ]; var searched = { e: 0, b: { x: 2, y: 5 } }; //Check an existing userId console.log(checkIfObjectExists(array, searched)); //Check a non existing userId console.log(checkIfObjectExists(array, { a: 0, b: { x: 1, y: 2 } })); 

The following IsExists() retun true if same object already exists and return false if same object not exists.

function IsExists(YourList,Object ) {
        var i;
        for (i = 0; i < YourList.length; i++) {
            if (YourList[i].c === Object .c && YourList[i].b === Object .b) {
                return true;
            }
        }

        return false;
    }

call you function like:

    var NewObject={
     e:0, 
     b:{x:2,y:5}
    }

if (!IsExists(array ,NewObject.b))
{
array .push(NewObject);
}

if the IsExists(array ,NewObject.b)return false then push this object into array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM