Here is an array of objects:
var array = [{ first: "Romeo", last: "Capulet" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }]
Here is an object:
var obj = {last: "Capulet}
Trying to find an object by its key, if two keys of two objects are the same! If this object obj is contained within above array of object by one of its properties and value, it suppose to return entire object of above mentioned array of object. For example in this case it should return an array of two objects because two objects contain property "last" with its value "Capulet"!
[{ first: "Romeo", last: "Capulet" }, { first: "Tybalt", last: "Capulet" }]
This is my code:
function objectFindByKey(array, obj){
var array1 = [];
for(var i = 0; i<array.length;i++){
array1.push(Object.entries(array[i]));
var a2 = JSON.stringify(array1);
var a3 = JSON.stringify(obj);
if(a2.includes(a3)){
return array1[i];
};
};
};
To be able to compare two objects I used JSON.stringify() method because in that case if I stringify an array of objects. Unfortunately it returns "undefined" at the end!