Javascript: Filter() for Objects

JavaScript: filter() for Objects

Never ever extend Object.prototype.

Horrible things will happen to your code. Things will break. You're extending all object types, including object literals.

Here's a quick example you can try:

    // Extend Object.prototype
Object.prototype.extended = "I'm everywhere!";

// See the result
alert( {}.extended ); // "I'm everywhere!"
alert( [].extended ); // "I'm everywhere!"
alert( new Date().extended ); // "I'm everywhere!"
alert( 3..extended ); // "I'm everywhere!"
alert( true.extended ); // "I'm everywhere!"
alert( "here?".extended ); // "I'm everywhere!"

Instead create a function that you pass the object.

Object.filter = function( obj, predicate) {
let result = {}, key;

for (key in obj) {
if (obj.hasOwnProperty(key) && !predicate(obj[key])) {
result[key] = obj[key];
}
}

return result;
};

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);

Filter an array of objects by another object of filters

You can achieve this result using filter, Object.keys, and every.

You have to use filter and pass predicate that tell whether it is included in the final result.

In predicate, loop over all properties on the filters object and match if it is present in data or not. Simple

data.filter((o) =>Object.keys(filters).every((k) => filters[k] === o[k]));

const data = [{
level: "1",
objectId: "11",
objectIdNo: "320",
wpId: "123",
},
{
level: "2",
objectId: "12",
objectIdNo: "321",
wpId: "123",
},
{
level: "2",
objectId: "13",
objectIdNo: "322",
wpId: "120",
},
];

const filters = {
level: "2",
wpId: "123",
};

const result = data.filter((o) =>
Object.keys(filters).every((k) => filters[k] === o[k])
);
console.log(result);

How to filter an array in array of objects in Javascript?

filter() -> uses a callback function the return value of which decides what will be returned in the filtered array. If return value is true, the item is included in the resultant array.

includes() -> searches for something in an array of items using == equality

const books = [{
id: "1",
title: "Book title",
areas: ["horror", "mystery"]
}, {
id: "2",
title: "Book title 2",
areas: ["friendship", "love", "history"]
},
{
id: "2",
title: "Book title 3",
areas: ["friendship", "scifi"]
}
];

const filterValue = "horror";
const filteredBooks = books.filter(val => val.areas.includes(filterValue));
console.log(filteredBooks);

How to filter through an array of objects and only get the objects whose entries do not equal any entry from another array's objects?

The following approach is based on a single reduce task where the reducer function incorporates a some based filter/comparison task.

The filter/match process is implemented in a way that a match is assumed as soon as the criteria of just one filter-configuration matches a single item property.

function isMatchingItem({ type: key, value }, item) {
return item[key] === value;
}
function collectNonMatchingItem({ filters = [], result = [] }, item) {
if (
!filters.some(filter => isMatchingItem(filter, item))
) {
result.push(item);
}
return { filters, result };
}

const uniqueProducts = [
{ category: 'radio', price: '50', manufacturer: 'sony', production_date: '2020/05/30' },
{ category: 'radio', price: '70', manufacturer: 'philips', production_date: '2020/05/30' },
{ category: 'tv', price: '500', manufacturer: 'sony', production_date: '2020/05/30' },
{ category: 'tv', price: '650', manufacturer: 'philips', production_date: '2020/05/30' },
{ category: 'console', price: '900', manufacturer: 'sony', production_date: '2020/05/30' },
{ category: 'console', price: '700', manufacturer: 'nintendo', production_date: '2020/05/30' },
];
const selectedFilters = [
{ type: 'manufacturer', value: 'sony', status: true },
{ type: 'category', value: 'radio', status: true },
];

const result = uniqueProducts.reduce(collectNonMatchingItem, {

filters: selectedFilters,
result: [],

}).result;

console.log({ result });
.as-console-wrapper { min-height: 100%!important; top: 0; }

How to filter object array using an array in JS?

You could use Array.includes instead of iterating over my_array:

var ob_array = [{
'a': 1,
'col_2': 'abc'
},
{
'a': 2,
'col_2': 'xyz'
},
{
'a': 3,
'col_2': 'jkl'
}
];

var my_array = [1, 2];

console.log(ob_array.filter(ob => !my_array.includes(ob.a)))

Filter an array of objects with keys

you can do this:

array.filter((item)=>{return item.someKey==='valueYouWant'})

in your example you can do something like this:

const filtered=array.filter((item)=>{return item.categoryId<22})

Filter object properties by key in ES6

If you have a list of allowed values, you can easily retain them in an object using:

const raw = {  item1: { key: 'sdfd', value:'sdfd' },  item2: { key: 'sdfd', value:'sdfd' },  item3: { key: 'sdfd', value:'sdfd' }};
const allowed = ['item1', 'item3'];
const filtered = Object.keys(raw) .filter(key => allowed.includes(key)) .reduce((obj, key) => { obj[key] = raw[key]; return obj; }, {});
console.log(filtered);

Filter object by value

You could use filter() on one of the arrays and find() to filter out the objects from that array with ids that don't occur in the other array.

let oArr1 = [{id: 15, name: "name1"}, {id: 0, name: "name2"}, {id: 98, name: "name3"}];
let oArr2 = [{id: 2, action: "action"}, {id: 88, action: "action"}, {id: 0, action: "action"}];

const result = oArr1.filter(x => !oArr2.find(y => y.id === x.id));

console.log(result);


Related Topics



Leave a reply



Submit