0

I have an array containing objects.

I want to search the array using an if statement for objects that have a certain property and create a separate array containing only those objects.

var firstArray = [...]

for (var a = 0; a < firstArray.length; a++) {
  if (firstArray[a].name == 'index.png') {
    // create secondArray here
  }
}

Thanks for your help!

r_cahill
  • 577
  • 3
  • 9
  • 20
  • [`Array#filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter). – Erazihel Aug 14 '17 at 12:41
  • please provide sample data and where did you stuck. There is no need to do this. There are already built in methods like filter – Sagar V Aug 14 '17 at 12:41

3 Answers3

0

Just use a filter

var secondArray = firstArray.filter(x => x.name == 'index.png')
Pac0
  • 21,465
  • 8
  • 65
  • 74
0

var firstArray = [{
  'name': 'A'
}, {
  'name': 'B'
}, {
  'name': 'C'
}]
var newArray = [];

for (name in firstArray) {
  if (firstArray[name].name == 'A') {
    newArray = firstArray[name];
    console.log(newArray)
  }
}

Kindly check this snippet.

-1

You can use this way

var obj = {'el1': 1, 'el2': 2};
var firstArray = [{'el1': 1, 'el2': 2}, {'el3': 1, 'el4': 2}]
var searchTerm = 'el1';
for(var a=0; a<firstArray.length; a++){
  for(var key in firstArray[a]){
    if(key == searchTerm){
      // do whatever you want to do. 
    console.log('key = ', key, 'value = ', obj[key]);
    }
  }
}
atiq1589
  • 2,227
  • 1
  • 16
  • 24