0

I have an array of objects and need to find whether an array of objects contain a given value for any property? (It can be for any property).

E.g.:

[
    {product_name: "iphone 7s " , cost: "122"  , type: "product" },  
    {name: "John Snow " , email: "[email protected]"  , type: "contact"}, 
    {seller_name: "John Smith " , brand: "Xbrand"  , type: "seller"}
]; 

I need a function to return the last two objects in which value "John" exists.

1
  • Try iterating over the array, then iterate over the object while in ther first loop and search for the value ! Commented Oct 2, 2017 at 12:44

2 Answers 2

3

You could filter the array an check if a value of the object contains the wanted string.

var data = [{ product_name: "I phone 7s ", cost: "122", type: "product" }, { name: "Joh Snow ", email: "[email protected]", type: "contact" }, { seller_name: "Joh Smith ", brand: "Xbrand", type: "seller" }],
    result = data.filter(o => Object.values(o).some(s => s.includes('Joh')));
    
console.log(result);

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

Comments

0

What you could do is loop through the array of objects, and check if the property value contains your text. Then you can add that to an array and take the last 2 from that array using slice.

For example:

var objects = [
    {product_name: "iphone 7s ", cost: "122", type: "product"},
    {name: "John Snow ", email: "[email protected]", type: "contact"},
    {seller_name: "John Smith ", brand: "Xbrand", type: "seller"}
];

function getObjectsContaining(coll, value) {
    var results = [];

    for (var i = 0; i < coll.length; i++) {
        var obj = coll[i];
        for (var property in obj) {
            if (obj.hasOwnProperty(property) && obj[property].indexOf(value) !== -1) {
                results.push(obj);
            }
        }
    }
    return results.slice(-2);
}

console.log(getObjectsContaining(objects, "John"));

1 Comment

Why results.slice(-2) ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.