Home > Software design >  Find all matching elements within an array of objects with unknown key
Find all matching elements within an array of objects with unknown key

Time:10-10

I have an array of objects like this:

[
    {"firstKey":"firstValue","secondKey":"secondValue"},
    {"thirdKey":"thirdValue","forthKey":"forthValue"}
]

and object like

{"thirdKey":"thirdValue","forthKey":"forthValue"}

I want to check if this object exists in an array of objects or no
NOTE: The keys of objects are generated dynamically and I don't know the name of the keys.

CodePudding user response:

SOLUTION: (only works when two the keys are in same order)

Use find() and JSON.stringify()

const arr = [
    {"firstKey":"firstValue","secondKey":"secondValue"},
    {"thirdKey":"thirdValue","forthKey":"forthValue"}
];

const look = {"thirdKey":"thirdValue","forthKey":"forthValue"}
const look2 = {"thirdKey":"fourthValue","forthKey":"forthValue"}

let exists1 = arr.find((x) => JSON.stringify(x) === JSON.stringify(look)) === undefined ? false : true ;

let exists2 = arr.find((x) => JSON.stringify(x) === JSON.stringify(look2)) === undefined ? false : true ;

console.log(exists1);
console.log(exists2);

EDIT:

JSON.stringify(x) === JSON.stringify(y) will only work when strings are in same order. Otherwise you will have to use a complex function to compare the two objects. Check

CodePudding user response:

You can use JSON.stringify() to compare objects:

const arr = [
    {"firstKey":"firstValue","secondKey":"secondValue"},
    {"thirdKey":"thirdValue","forthKey":"forthValue"}
]

const needle = {"thirdKey":"thirdValue","forthKey":"forthValue"}

console.log( arr.filter(o => JSON.stringify(o) === JSON.stringify(needle)) )

CodePudding user response:

What you need to do is get the keys of the object, using Object.keys(object), and for every object in the array do the same, than compare them, as follows:

function findEqual(object, array) {
    var objectKeys = Object.keys(object);
    for (var i = 0; i < array.length; i  ) {
        var currObjectKeys = Object.keys(array[i]);
        if (currObjectKeys.length !== objectKeys.length) {
            continue;
        }
        var found = true;

        for (var j = 0; j < objectKeys.length; j  ) {
            if (objectKeys[j] !== currObjectKeys[j]) {
                found = false;
                break;
            }
            if (object[objectKeys[j]] !== array[i][objectKeys[j]]) {
                found = false;
                break;
            }
        }
        if (found) {
            return i;
        }
    }
    
    return -1;
}

CodePudding user response:

const objExist = (arr, obj) => {
 return arr.reduce((acc, item)=>{
   const found = JSON.stringify(item) === JSON.stringify(obj); 
   if (found) { acc = 1}
   return acc
   }, 0)
}
  • Related