-2

I am having an javascript array with objects in it:

var array;
array[{name: "Peter",class: "7"},{name: "Klaus",class: "3"}];

How to find out if in this array is the name Peter?

EDIT: I want to have something like this

if (array.find("Peter"))
{
  ...
}
Tim Jansen
  • 73
  • 10

6 Answers6

1
var array = [{name: "Peter",class: "7"},
             {name: "Klaus",class: "3"}];

var filtered = array.filter(function(item){
    return item.name == 'Peter';
});

// filtered now equals [{name: "Peter",class: "7"}]
Chris Charles
  • 4,406
  • 17
  • 31
1

Use find.

arr.find(row => row.name === 'Peter');

Don't forget to use the polyfill in the link if your targeted browsers don't support this method.

Lewis
  • 14,132
  • 12
  • 66
  • 87
0

First you should correct your array declaration

var array = [{name: "Peter",class: "7"},{name: "Klaus",class: "3"}];

And you should try it

array.find(function(o) { return o.name==="Klaus" })

Hope this help :-)

Arcord
  • 1,724
  • 1
  • 11
  • 16
0
var students = [{name: "Peter", class: "7"}, {name: "Klaus", class: "3"}];
students.find( student => { return student.name === 'Peter' });

function find(arr, key, value) {
    return arr.find( item => {
        return item[key] === value;
    }) !== undefined;
}


console.log(find(students, 'name', 'Peter'));
nham
  • 161
  • 5
0

Some sample code in both ES6 and ES5!

// Search for "Peter" in the name field
if (arr.find(row => row.name === 'Peter')) {
    console.log('found');
} else {
    console.log('not found');
}

// Same function in ES5
arr.find(function(row) {
    console.log(row);
    if (row.name === 'Peter') {
    console.log('ES5: found');
  }
});
teododo
  • 1
  • 1
-1
array.findIndex(e => e['name'] === 'Peter')

One of AngularJS solutions