How to filter array when object key value is in array
You can do it with Array.prototype.filter()
,
var data = { records : [{ "empid": 1, "fname": "X", "lname": "Y" }, { "empid": 2, "fname": "A", "lname": "Y" }, { "empid": 3, "fname": "B", "lname": "Y" }, { "empid": 4, "fname": "C", "lname": "Y" }, { "empid": 5, "fname": "C", "lname": "Y" }] }
var empIds = [1,4,5]
var filteredArray = data.records.filter(function(itm){
return empIds.indexOf(itm.empid) > -1;
});
filteredArray = { records : filteredArray };
If the callBack
returns a true
value, then the itm
passed to that particular callBack
will be filtered out. You can read more about it here.
Filter array of objects on key from array of values JavaScript
Use map()
to loop over the array of objects and create a new array with the result of filtering the object properties.
You should be using FilterArray.includes()
, not key.includes()
.
const finalArray = [ { "cbsa_cde": "33460", "cbsa_nm": "Minneapolis-St. Paul-Bloomington, MN-WI", "countycode": "27053", "hh_50k_100k_201612": 71, "hh_50k_100k_201706": 86, "hh_50k_100k_201712": 60, "hh_50k_100k_201806": 37, "hh_50k_100k_201812": 49, "hh_50k_100k_201906": 35, "hh_50k_100k_201912": 38, "hh_50k_100k_202006": 46, "hh_50k_100k_202012": 58, "hh_100k_250k_201612": 120, "hh_100k_250k_201706": 121, "hh_100k_250k_201712": 153, "hh_100k_250k_201806": 126, "hh_100k_250k_201812": 126, "hh_100k_250k_201906": 125, "hh_100k_250k_201912": 120, "hh_100k_250k_202006": 99, "hh_100k_250k_202012": 84}, { "cbsa_cde": "33460", "cbsa_nm": "Minneapolis-St. Paul-Bloomington, MN-WI", "countycode": "27053","hh_50k_100k_201612": 20, "hh_50k_100k_201706": 33, "hh_50k_100k_201712": 22, "hh_50k_100k_201806": 41, "hh_50k_100k_201812": 52, "hh_50k_100k_201906": 45, "hh_50k_100k_201912": 40, "hh_50k_100k_202006": 41, "hh_50k_100k_202012": 50, "hh_100k_250k_201612": 99, "hh_100k_250k_201706": 108, "hh_100k_250k_201712": 130, "hh_100k_250k_201806": 84, "hh_100k_250k_201812": 90, "hh_100k_250k_201906": 97, "hh_100k_250k_201912": 89, "hh_100k_250k_202006": 95, "hh_100k_250k_202012": 87} ],
filterArray = [ "HH_50K_100K_201612", "HH_50K_100K_201706", "HH_100K_250K_201612", "HH_100K_250K_201706" ];
const result = finalArray.map(jsonData =>
Object.fromEntries(Object.entries(jsonData).filter(([key, value]) => filterArray.includes(key.toUpperCase()))));
console.log(result);
Filter an array of objects according to the name of the key in the objects
Use the in
operator to check if a property exists on the object:
const dataArray = [{"name":"David"},{"location":"New York"},{"name":"Jenna"}];
// name exists on the object
console.log(dataArray.filter(item => 'name' in item));
// or location doesn't exist on the object
console.log(dataArray.filter(item => !('location' in item)));
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})
Filtering array of objects if specific key contains search term
You don't need the Object.keys
loop.
const someArrayOfObjects = [
{ id: '1', name: 'Something' },
{ id: '2', name: 'Another' },
{ id: '3', name: 'Lets do one more' },
];
let key = 'name';
let searchTerm = 'th';
const res = someArrayOfObjects.filter(o =>
o[key].toLowerCase().includes(searchTerm.toLowerCase()));
console.log(res);
filter array of objects based on separate object keys, values
You could filter as follows:
const FIRST_ARRAY = [ { name: 'Simon', age: 32, occupation: 'Student' }, { name: 'Vera', age: 22, occupation: 'Developer' }];
const FILTERS = { name: 'Simon', age: 32, occupation: ''};
const filtered = FIRST_ARRAY.filter(person => Object.entries(FILTERS) .every(([key, val]) => val !== '' ? person[key] === val : true)); console.log(filtered);
Filter objects in array by key-value pairs
I think you're looking for something like this? Would basically be doing a string.includes match on the value of each key in your filter object--if one of the key values matches then it will be included in the result. If you wanted the entire filter object to match you could do .every
instead of .some
...
const data = [
{
id: 'a',
name: 'Alan',
age: 10
},
{
id: 'ab',
name: 'alanis',
age: 15
},
{
id: 'b',
name: 'Alex',
age: 13
}
]
const filter = { id: 'a', name: 'al' }
function filterByObject(filterObject, data) {
const matched = data.filter(object => {
return Object.entries(filterObject).some(([filterKey, filterValue]) => {
return object[filterKey].includes(filterValue)
})
})
return matched
}
console.log(filterByObject(filter, data))
JavaScript How to filter array of objects by dynamic key?
Already Data
[
{item1: { key: 'sdfd', value:'sdfd' }},
{item2: { key: 'sdfd', value:'sdfd' }},
{item3: { key: 'sdfd', value:'sdfd' }}
]
Want Data
Want the data from target
, when target is item1
:
[
{item1: { key: 'sdfd', value:'sdfd' }}
]
Current Code
let arr = [
{item1: { key: 'sdfd', value:'sdfd' }},
{item2: { key: 'sdfd', value:'sdfd' }},
{item3: { key: 'sdfd', value:'sdfd' }}
]
let target = 'item1'
// result array
let want = [
{item1: { key: 'sdfd', value:'sdfd' }},
]
Filter an array of objects by key and nested value in JavaScript
This looks a little unwieldy but it's pretty simple. First, map
your array and filter out any value.date
that do not fit in the range. Then simply filter out any parent elements that have a zero-length value array.
const filteredEvents = (from, to) => allEvents
.map( g =>
({...g,
value: g.value.filter(f =>
new Date(f.date).getTime() >= new Date(from).getTime() &&
new Date(f.date).getTime() <= new Date(to).getTime())
}))
.filter(f => f.value.length>0);
let allEvents = [{
key: "Dec 2021",
value: [{
id: 0,
date: "Dec 06 2021"
},
{
id: 1,
date: "Dec 01 2021"
},
],
},
{
key: "Nov 2021",
value: [{
id: 0,
date: "Nov 27 2021"
},
{
id: 1,
date: "Nov 23 2021"
},
{
id: 2,
date: "Nov 10 2021"
},
],
},
{
key: "Oct 2021",
value: [{
id: 0,
date: "Oct 27 2021"
},
{
id: 1,
date: "Oct 23 2021"
},
{
id: 2,
date: "Oct 10 2021"
},
],
},
];
const filteredEvents = (from, to) => allEvents
.map( g => ({...g, value: g.value.filter(f => new Date(f.date).getTime() >= new Date(from).getTime() && new Date(f.date).getTime() <= new Date(to).getTime())})).filter(f => f.value.length>0);
console.log(filteredEvents("Nov 15 2021", "Dec 04 2021"));
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: "3",
title: "Book title 3",
areas: ["friendship", "scifi"]
}
];
const filterValue = "horror";
const filteredBooks = books.filter(val => val.areas.includes(filterValue));
console.log(filteredBooks);
Related Topics
Finding Element's Position Relative to the Document
Random Alpha-Numeric String in JavaScript
Limit Concurrency of Promise Being Run
How to Get Class Object's Name as a String in JavaScript
Is <Boolean Expression> && Statement() the Same as If(<Boolean Expression>) Statement()
Date.Setmonth' Causes the Month to Be Set Too High If 'Date' Is at the End of the Month
How to Log All Events Fired by an Element in Jquery
Fulfill (Don't Resolve) Promise with Another Promise
Node.Js Shell Command Execution
Facebook How to Check If User Has Liked Page and Show Content
How to Build Query String with JavaScript
Watch Multiple $Scope Attributes
How to Remove the Decimal Part from JavaScript Number