Object and Like Array Search in Javascript

Asked

Viewed 77 times

1

I’m trying to get the value of a key inside an object inside an array, I can bring all the values of the key detyerminada, what I couldn’t get because I didn’t understand it properly was to bring only the value of an object if another object is with the value I want, type a like in mysql

This is my Object Array

let meuArray = [
  { index: 1, bestOffer: true, title: plan[1].friendly },
  { index: 2, bestOffer: false, title: plan[2].friendly }
]

And I seek this way

this.meuArray.map(o => o.title)

It brings me all the titles separated by a comma , I tried to do so

this.meuArray.map(o => o.bestOffer && o.title)

and he brought me just what I wish, which is bestoffer’s title true however exhibited false comma-separated , together with the title in question as I proceed to get only the title where bestoffer is true using this example this.meuArray.map(o => o.title) as if it were a like in mysql? I tried in, indexof, has among others

  • 2

    What you want to do is filter an object, no map the same.

1 answer

2


Hello, I believe you are looking for the function filter. The use of it is very simple, and can be chained to do the mapping as in your own example. It would look something like this:

this.meuArray
    .filter(o => o.bestOffer)
    .map(o => o.title)
  • worked beautifully, I just didn’t know how to use, so are two blocks, first filter after map, thank you very much, what I was not understanding

  • Exactly Roberto! Then take a look at this filter documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter It’s certainly worth reading just a read.

  • Thank you Murillo de Morais

Browser other questions tagged

You are not signed in. Login or sign up in order to post.