2

I know to find a value exist or not in an array I can use indexOf, but how to do it with an array of object?

const x = [{
  "id": "roadshows",
  "name": "Roadshows"
}, {
  "id": "sporting_events",
  "name": "Sporting Events"
}]

console.log( x.indexOf('roadshows') ) // don't work
Alan Jenshen
  • 3,159
  • 9
  • 22
  • 35

5 Answers5

7

Since this is tagged , here's an ES6 array method: Array#findIndex():

const x = [{
  "id": "roadshows",
  "name": "Roadshows"
}, {
  "id": "sporting_events",
  "name": "Sporting Events"
}]

console.log( x.findIndex( o => o.id === 'roadshows' ) )

If you want a more re-useable way of doing this, consider creating a factory isId(id):

function isId(id) {
  return (o) => o.id === id;
}

const x = [{
  "id": "roadshows",
  "name": "Roadshows"
}, {
  "id": "sporting_events",
  "name": "Sporting Events"
}]

console.log( x.findIndex( isId('roadshows') ) )

This is referred to as a "factory" because it is a function that returns a function with the passed parameter in its scope.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
0

You have to loop through since you have object's inside array.

for(var i = 0; i < x.length; i++) {
    if (x[i].id== 'roadshows') {
        console.log(i);
        break;
    }
}

Or if you just checking that the object exist with that id, filter is handy

if (x.filter(function(e) x.id== 'roadshows').length > 0) {
  // Yay. Do Something
}
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

manually I'd do something like this:

for(let item of x) {
 if ( item.hasOwnProperty('id') && item['id'] == 'roadshows' ) {   
    //do your stuff here
 }
}
Korgen
  • 5,191
  • 1
  • 29
  • 43
0

You have a couple of options.

First and foremost, findIndex. You pass it a function that tests if an element is what you are looking for, it returns the index of the first element that makes that function return true.

x.findIndex((o) => o.id === 'roadshows');

const x = [{
  "id": "roadshows",
  "name": "Roadshows"
}, {
  "id": "sporting_events",
  "name": "Sporting Events"
}];

console.log(x.findIndex((o) => o.id === 'roadshows'));

Another option is first mapping the relevant property to an array and searching in that one.

x.map((o) => o.id).indexOf('roadshows');

const x = [{
  "id": "roadshows",
  "name": "Roadshows"
}, {
  "id": "sporting_events",
  "name": "Sporting Events"
}];

console.log(x.map((o) => o.id).indexOf('roadshows'));
Just a student
  • 10,560
  • 2
  • 41
  • 69
0

And if you can use es6 and want to return the object in question, then there is always Array.prototype.find()

x.find( item => { return item.id === "roadshows" } )

// returns {id: "roadshows", name: "Roadshows"}
ippi
  • 9,857
  • 2
  • 39
  • 50