0

Have some data:

[
 {
   property1: 1,
   property2: 2,     
 },
 {
   property1: 1,
   property2: 3,     
 },
 {
   property1: 2,
   property2: 3,     
 }
]

I need to get all objects of this array where property1=1. Is there more easier or shorter way to do this than something like:

 for(var i=0;i<array.length;i++){
   if(array[i]["property1"]==1) ....//some action
 }

Like in jquery I can use selector for DOM elements, if I need to get all span's with property1=1 I use $("span[property1=1]").each....

kliukovking
  • 569
  • 1
  • 5
  • 16

3 Answers3

2

You can just filter the array with Array.filter based on the property property1

var arr = [
   { property1: 1, property2: 2 },
   { property1: 1, property2: 3 },
   { property1: 2, property2: 3 }
];

var res = arr.filter( x => x.property1 === 1);

console.log(res)

Array.filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true.

Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • It would be a lot more helpful than just saying 'filter it' if you would explain. – Andrew Li Jul 20 '17 at 16:54
  • 1
    @AndrewLi - There's not much to explain, it's one line that filters based on a property? – adeneo Jul 20 '17 at 16:55
  • 2
    Say 'it filter based on the result of calling the callback on each element of the array' and how the return value is a boolean on whether it's kept... there are just too many code-dump posts in the JS tag – Andrew Li Jul 20 '17 at 16:56
  • 2
    @AndrewLi - If you think I'm not explaining it well enough, post your own answer. – adeneo Jul 20 '17 at 16:57
1

You can loop the array as you are doing right now. All you need to do is to create a new array and to push the found objects to that array.

However, there is array's filter() function:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

var filteredArray = array.filter(function(obj){
   return obj.property1 === 1;
})
Boghyon Hoffmann
  • 17,103
  • 12
  • 72
  • 170
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
-4

kicked out this: Why not use lodash? like:

 _.filter(arr, {property1: 1})

use arr.filter(o => { return o.property1 === 1; })
4b0
  • 21,981
  • 30
  • 95
  • 142