How to Filter Object Array Based on Attributes

How to filter object array based on attributes?

You can use the Array.prototype.filter method:

var newArray = homes.filter(function (el) {
return el.price <= 1000 &&
el.sqft >= 500 &&
el.num_of_beds >=2 &&
el.num_of_baths >= 2.5;
});

Live Example:

var obj = {

'homes': [{

"home_id": "1",

"price": "925",

"sqft": "1100",

"num_of_beds": "2",

"num_of_baths": "2.0",

}, {

"home_id": "2",

"price": "1425",

"sqft": "1900",

"num_of_beds": "4",

"num_of_baths": "2.5",

},

// ... (more homes) ...

]

};

// (Note that because `price` and such are given as strings in your object,

// the below relies on the fact that <= and >= with a string and number

// will coerce the string to a number before comparing.)

var newArray = obj.homes.filter(function (el) {

return el.price <= 1000 &&

el.sqft >= 500 &&

el.num_of_beds >= 2 &&

el.num_of_baths >= 1.5; // Changed this so a home would match

});

console.log(newArray);

How to filter an array based on property value, or existence of properties

You're looking for Object#hasOwnProperty. Specifially, you're looking to filter your array to only the items which have the property season which you can accomplish like this:

const cities = [
{ "population": 121321313, "location": "American city in the East" },
{ "season": "winter", "population": 54646546, "location": "Canadian city in the East" },
{ "population": 6546467,"location": "American city in the West"},
{ "season": "fall", "population": 145313, "location": "American city in the South" },
{ "population": 12673, "location": "Canadian city2 in the East" },
{ "population": 141313, "location": "Canadian city in the South" },
{ "season": "fall", "population": 1264473, "location": "Canadian city4 in the East" },
{ "population": 12673, "location": "Canadian city6 in the South" }
];

const filteredCities = cities.filter(x => x.hasOwnProperty("season"));

console.dir(filteredCities);

How to filter an array of objects by attribute

You can use a small trick here as the condition:

sections.map(section=>section.id).includes(directionId)

    finalistsCollection = [

{ name: 'Ann' , sections: [{id: '132', name: 'someName'}, {id: '456', name: 'someName'}] },

{ name: 'Jack' , sections: [{id: '798', name: 'someName'}] },

{ name: 'Morgan', sections: [{id: '456', name: 'someName'}] },

{ name: 'Billy', sections: [{id: '132', name: 'someName'}, {id: '456', name: 'someName'}]},

{ name: 'Monica', sections: [{id: '798', name: 'someName'}] }

]

function filter(directionId) {

return finalistsCollection.filter((item) =>

item.sections.map(section=>section.id).includes(directionId))

}



console.log(filter('798'))

console.log(filter('456'))

console.log(filter('112'))

How to filter out items in array of objects based on item in property array in JavaScript

You can filter menus array using Array.prototype.filter() by checking if locations property includes the desired MENU_EN with Array.prototype.includes():

Code:

const menus = [{id: 1,title: 'English',locations: ['MENU', 'MENU_EN']},{id: 2,title: 'Spanish',locations: ['MENU', 'MENU_SP']},{id: 3,title: 'German',locations: ['MENU', 'MENU_DE']},{id: 4,title: 'German and english',locations: ['MENU', 'MENU_EN', 'MENU_DE']},]

const filteredMenus = menus.filter(({ locations }) => locations.includes('MENU_EN'))

console.log(filteredMenus)

Filter an array based on an object property

You could use array's filter() function:

function filter_dates(event) {
return event.date == "22-02-2016";
}

var filtered = events.filter(filter_dates);

The filter_dates() method can be standalone as in this example to be reused, or it could be inlined as an anonymous method - totally your choice =]

A quick / easy alternative is just a straightforward loop:

var filtered = [];
for (var i = 0; i < events.length; i++) {
if (events[i].date == "22-02-2016") {
filtered.push(events[i]);
}
}

How to filter an array of objects only by name property? - Javascript

Array.filter will filter the array removing unwanted items, You're looking for Array.map to keep the same array length changing the value of each element of the array :

let movies = [{
'name': 'Jumanji',
'duration': 120
},
{
'name': 'Harry P',
'duration': 60
},
{
'name': 'Toy Story',
'duration': 240
}
];

let newAr = movies.map((item, index, arr) => {
return item.name
})

console.log('newAr', newAr)

Filter array of objects whose any properties contains a value

You could filter it and search just for one occurence of the search string.

Methods used:

  • Array#filter, just for filtering an array with conditions,

  • Object.keys for getting all property names of the object,

  • Array#some for iterating the keys and exit loop if found,

  • String#toLowerCase for getting comparable values,

  • String#includes for checking two string, if one contains the other.

function filterByValue(array, string) {

return array.filter(o =>

Object.keys(o).some(k => o[k].toLowerCase().includes(string.toLowerCase())));

}

const arrayOfObject = [{ name: 'Paul', country: 'Canada', }, { name: 'Lea', country: 'Italy', }, { name: 'John', country: 'Italy' }];

console.log(filterByValue(arrayOfObject, 'lea')); // [{name: 'Lea', country: 'Italy'}]

console.log(filterByValue(arrayOfObject, 'ita')); // [{name: 'Lea', country: 'Italy'}, {name: 'John', country: 'Italy'}]
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to filter an array of objects by unique ID and unique name?

You can simply use && to include additional criteria that needs to be met: in your example, you want both the id and name to match:

const filteredData = data.filter((value, index, self) => 
self.findIndex(v => v.id === value.id && v.name === value.name) === index
);

If you have multiple keys you want to consider and you don't want to write multiple && statements, you can simply store the keys in an array, and then use Array.prototype.every() to enforce the match:

const keys = ['id', 'name'];
const filteredData = data.filter((value, index, self) =>
self.findIndex(v => keys.every(k => v[k] === value[k])) === index
);

See proof-of-concept below:

const data = [{
id: 1234,
name: 'Name1'
},
{
id: 5678,
name: 'Name1'
},
{
id: 1234,
name: 'Name1'
},
{
id: 5678,
name: 'Name2'
},
];

const keys = ['id', 'name'];
const filteredData = data.filter((value, index, self) =>
self.findIndex(v => keys.every(k => v[k] === value[k])) === index
);

console.log(filteredData);


Related Topics



Leave a reply



Submit