var persons = [
{name : "jak" , age:20},
{name : "hasan" , age: 15},
{name : "reza" , age:18}
];
function adult(el,index,arr){
if (el.age >= 18)
return el.name;
}
document.getElementById("x").innerHTML = persons.filter(adult);
}
I expected jak and reza , but i see [object object] [object object].
var persons = [
{name : "jak" , age:20},
{name : "hasan" , age: 15},
{name : "reza" , age:18}
];
function adult(el,index,arr){
if (el.age >= 18)
return el.name;
}
document.getElementById("x").innerHTML = persons.filter(adult);
}
I expected jak and reza , but i see [object object] [object object].
Share Improve this question edited Apr 18, 2016 at 22:24 Mike Cluck 32.5k13 gold badges83 silver badges94 bronze badges asked Apr 18, 2016 at 22:19 EhsanEhsan 13k3 gold badges26 silver badges46 bronze badges2 Answers
Reset to default 4The filter needs to return true to keep the element or false otherwise.
See below:
var persons = [{
name: "jak",
age: 20
}, {
name: "hasan",
age: 15
}, {
name: "reza",
age: 18
}];
function adult(el, index, arr) {
if (el.age >= 18)
return true;
}
document.getElementById("x").innerHTML = persons.filter(adult).map(function(person) {
return person.name;
});
<div id='x'></div>
Reference: MDN
You're seeing [object Object], [object Object]
because you're trying to display an array of objects as a string. That's happening because you seem to think that filter
creates a string based on it's return value. That's not how filter
works. filter
takes a function which returns true
or false
and creates a new array with only the results that returned true
.
var adults = persons.filter(function(person) {
return person.age >= 18;
});
If you want to map certain elements in an array to something else you can use map
.
var adultNames = adults.map(function(person) {
return person.name;
});
Finally, to convert an array into a single string, you can use join
.
document.getElementById("x").innerHTML = adultNames.join('and');