3

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.

E_net4
  • 27,810
  • 13
  • 101
  • 139
MasterMind
  • 884
  • 8
  • 21
  • `array.find(x => x.something.includes("b"))` for partial match or `array.find(x => x.something === "b")` for exact match. – VLAZ Apr 20 '21 at 11:38
  • 1
    Both `filter` and `find` pass the element into the callback function. The array element is your object, so now all you need to do, is access a specific property of that object. What the example from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter does with the `length`, you want to do with `b`. – CBroe Apr 20 '21 at 11:39

3 Answers3

2

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

let resultWithSomethingB = array.filter(element => element.something === 'b')[0];
Vendel Serke
  • 135
  • 11
1

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" }))
Wimanicesir
  • 4,606
  • 2
  • 11
  • 30
1

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
Maverick Fabroa
  • 1,105
  • 1
  • 9
  • 15