-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!

2
  • 1
    do you want a new object? have you tried something? Commented Feb 20, 2021 at 12:03
  • Yes, I would like new object! Commented Feb 20, 2021 at 12:03

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

OP clarified later they want a new object.
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.