Search code examples
javascriptlodash

Filter map and return array of ids


I have this structure :

var entities = {
  1: {'name': 'Fred', 'age': 35},
  2: {'name': 'Hans', 'age': 47},
  3: {'name': 'Bert', 'age': 27}
}

I need something like :

var ids = entities.filter( p => p.age > 30);

which should return an array :

[1, 2]

Is there a convenient way to do this ? e.g. Lodash, etc ?


Solution

  • you can use the Object.keys combined with Array.prototype.filter

    var entities = {
      1: {'name': 'Fred', 'age': 35},
      2: {'name': 'Hans', 'age': 47},
      3: {'name': 'Bert', 'age': 27}
    }
    const result = Object.keys(entities).filter(key =>  entities[key].age > 30);
    console.log(result);