我正在使用包含对象的javascript数组:
var array;
array[{name: "Peter",class: "7"},{name: "Klaus",class: "3"}];
如何确定这个数组中的名字是Peter?
编辑:我希望有类似的东西if (array.find("Peter"))
{
...
}
答案 0 :(得分:1)
答案 1 :(得分:0)
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"}]
答案 2 :(得分:0)
首先你应该纠正你的数组声明
var array = [{name: "Peter",class: "7"},{name: "Klaus",class: "3"}];
你应该尝试一下
array.find(function(o) { return o.name==="Klaus" })
希望这个帮助: - )
答案 3 :(得分: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'));
答案 4 :(得分:0)
ES6和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');
}
});
答案 5 :(得分:-1)
array.findIndex(e => e['name'] === 'Peter')
AngularJS解决方案之一