Check if an array contains values from object and return them?

Viewed 707

I have an Array, say something like that:

var array = [{something:"a"},{something:"b"},{something:"c"}]

I now want to get the Object which contains "b". How can I do that?

Here's what I tried finding before : I found out array.filter and array.find with includes but I couldn't get a way on how to use it on a String inside Object inside an Array and not just strings inside an Array.

3 Answers

This will return the object as you asked (In case if it existing)

let resultWithSomethingB = array.filter(element => element.something === 'b')[0];

Use the array function filter to accomplish this:

var array = [{something:"a"},{something:"b"},{something:"c"}];

// Filter array based on .something
console.log(array.filter(a => { return a.something === "b" }))

In that case you can use array.filter:

let newObject = null;

const newArray = array.filter(function(item) {
    // Return an item if the something property is a "b"
    return item.something === "b";
});

if (newArray.length > 0) {
    // Returns the first element
    newObject = newArray[0];
}

// Use the newObject
Related