array filter json code example
Example 1: js filter array of objects by value
var heroes = [
{name: “Batman”, franchise: “DC”},
{name: “Ironman”, franchise: “Marvel”},
{name: “Thor”, franchise: “Marvel”},
{name: “Superman”, franchise: “DC”}
];
var marvelHeroes = heroes.filter(function(hero) {
return hero.franchise == “Marvel”;
});
Example 2: filtering json array in javascript
const data = [
{
name: 'Bob',
gender: 'male',
age: 34,
},
{
name: 'Carol',
gender: 'female',
age: 36,
},
{
name: 'Ted',
gender: 'male',
age: 38,
},
{
name: 'Alice',
gender: 'female',
age: 40,
},
];
const arr1 = data.filter(d => d.age > 37);
console.log('arr1', arr1);
const arr2 = data.filter(d => d.gender === 'female');
console.log('arr2', arr2);
const ageAndGender = d => d.age > 37 && d.gender === 'female';
const arr3 = data.filter(ageAndGender);
console.log('arr3', arr3);
Example 3: array.filter in javascript
const array = [2, 3, 4]
if (event.target.checked) {
newValue.push(option);
} else {
newValue = newValue.filter(item => item.id != option.id);
}
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);