-3

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!

Ivan Vrzogic
  • 157
  • 1
  • 8

2 Answers2

1

You can loop through the object keys and delete the property if condition matches:

var obj = {a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10};
Object.keys(obj).forEach(function(k){
  if(obj[k]<5){
    delete obj[k];
  }
});

console.log(obj);
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

You could filter the entries.

const
    object = { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10 };
    result = Object.fromEntries(Object
        .entries(object)
        .filter(([_, v])=> v >= 5)
    );

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392