Filter Json Object Array on Multiple Values or Arguments JavaScript

Filter JSON object array on multiple values or arguments javascript

You can write it in the following way. If you want to do exact search write a search function like this:

function search(term) {
return users.filter(({username, firstName, lastName}) => {
return username.toLowerCase() === term.toLowerCase() ||
firstName.toLowerCase() === term.toLowerCase() ||
lastName.toLowerCase() === term.toLowerCase()
})
}

Instead of comparing each key one can iterate all object properties using object.keys.

If you want to match each anything use following function

function search(term) {
return users.filter(({username, firstName, lastName}) => {
return username.toLowerCase().indexOf(term.toLowerCase()) > -1 ||
firstName.toLowerCase().indexOf(term.toLowerCase()) > -1 ||
lastName.toLowerCase().indexOf(term.toLowerCase()) > -1
})
}

This will even match searchTerm anywhere. Like if you use this as search('al'). It will return the first object, whereas the first function will need exact string like search('alice') to work.

const users = [{    "username": "Alice",    "firstName": "Alice-U",    "lastName": "Wonderland"  },  {    "username": "bob",    "firstName": "Bob-u",    "lastName": "Builder",  },  {    "username": "charly",    "firstName": "Charly-u",    "lastName": "Brown",  }]
function searchFull(term) { return users.filter(({ username, firstName, lastName }) => { return username.toLowerCase() === term.toLowerCase() || firstName.toLowerCase() === term.toLowerCase() || lastName.toLowerCase() === term.toLowerCase()
})
}

function search(term) { return users.filter(({ username, firstName, lastName }) => { return username.toLowerCase().indexOf(term.toLowerCase()) > -1 || firstName.toLowerCase().indexOf(term.toLowerCase()) > -1 || lastName.toLowerCase().indexOf(term.toLowerCase()) > -1
})
}
console.log(searchFull('alice'))console.log(search('al'))

How to filter for multiple values within a long list of JSON data in JS?

const filters = [{label: 'forSale', value: false}, {label: 'color', value: 'red'}];
const filteredArray = array.filter(item => filters.every(filter => item[filter.label] === filter.value))

or

const filters = {forSale: true, color: 'blue'}; 
const filteredArray = array.filter(item => {
let result = true;
for(let key in filters) {
if (item[key] !== filters[key]){
result = false;
break;
}
}
return result;
})

or

const filters = {forSale: true, color: 'blue'};
const filteredArray = array.filter(item => Object.keys(filters).every(key => item[key] === filters[key]))

Filtering multiple value with multiple key in json array using lodash

You could use plain Javascript and iterate the keys of the filterBy and the values.

var data = [{ VOTER: 1012, PARTY: "REPUBLICAN", PRECINCT: 2408, AGE_GROUP: "71 +", LAST_VOTED: "08/2006", YEARS_REG: 51, BALLOT_STATUS: "PERM" }, { VOTER: 1013, PARTY: "REPUBLICAN", PRECINCT: 2411, AGE_GROUP: "71 +", LAST_VOTED: "08/2006", YEARS_REG: 50, BALLOT_STATUS: "PERM" }, { VOTER: 1014, PARTY: "DEMOCRAT", PRECINCT: 2424, AGE_GROUP: "71 +", LAST_VOTED: "08/2006", YEARS_REG: 50, BALLOT_STATUS: "PERM" }, { VOTER: 1015, PARTY: "DEMOCRAT", PRECINCT: 2418, AGE_GROUP: "71 +", LAST_VOTED: "08/2006", YEARS_REG: 50, BALLOT_STATUS: "POLL" }, { VOTER: 1109, PARTY: "AMERICAN INDEP", PRECINCT: 2404, AGE_GROUP: "71 +", LAST_VOTED: "08/2006", YEARS_REG: 34, BALLOT_STATUS: "POLL" }, { VOTER: 1111, PARTY: "DECLINED", PRECINCT: 2414, AGE_GROUP: "71 +", LAST_VOTED: "08/2006", YEARS_REG: 34, BALLOT_STATUS: "POLL" }],    filterBy = { PARTY: ["REPUBLICAN", "DEMOCRAT"], BALLOT_STATUS: ["PERM", "POLL"] },    result = data.filter(function (o) {        return Object.keys(filterBy).every(function (k) {            return filterBy[k].some(function (f) {                return o[k] === f;            });        });    });
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to filter json data with multiple includes values

I gave you two return statements to choose from, depending on if you want to match all parts or at least one part out of what was typed in:

const filterFunction = (a) => {
if(includeKeyword)
const parts = userInput.split(",");
// if you need the returned element to match *all* parts (AND)
return parts.every(p => a.text.includes(p.trim());

// if you need it to match *at least one* part (OR)
return parts.some(p => a.text.includes(p.trim());
}
};

filter json array based on multiple arguments including lists

You can try this on. Study about method filter in javascript to know what the code below does.

  const array = [{ sector_code: ..., listed_in: ... }]; // your array
const listed_inilter = ['KSE100', 'KMIALLSHR'];
const sector_code = ['0833', '0824'];

function array_subset() {
return array.filter(element => {
const is_listed = listed_inilter.some(item => element.listed_in.includes(item));

const is_sector = sector_code.includes(element.sector_code);

return (is_listed || is_sector)
});
}

console.log(array_subset()); // output the filtered list

How to filter JSON data based on multiple criteria in JavaScript?

You can use every for AND and some for OR. In your case you want to go thru the list of keys (so every for AND) and then check if the value exists in the search array. indexOf should do the job:

let jsonData = [  {"sn": "234234234", "pn": "1014143", "mft": "hello world", "sl": "GG07", "vtv": "Yes"},  {"sn": "324234234", "pn": "101423131143", "mft": "hello world 1", "sl": "GG08", "vtv": "Yes"}]  let query = {  mft: [],  sl: ["GG08"],  vtv: ["No"]}console.log(find_in_object(jsonData, query)); //returns one
let query2 = { sn: ['T234834U', 'T23423423'], pn: ['1014114', '21412342'], mft: ['Sbasdfa', 'asdfaser'], sl: ['BB03', 'SFD04'], vtv: ['Yes']}console.log(find_in_object(jsonData, query2)); //returns none
function find_in_object(my_array, my_criteria) { return my_array.filter(function(obj) { return Object.keys(my_criteria).every(function(key) { return (Array.isArray(my_criteria[key]) && (my_criteria[key].some(function(criteria) { return (typeof obj[key] === 'string' && obj[key].indexOf(criteria) === -1) })) || my_criteria[key].length === 0); }); });}

Filtering array of objects by multiple parameters

Please find array.reduce implementation of same.

const arr = [
{ name: "1", category: "TV", region: "US" },
{ name: "2", category: "TV", region: "SE" },
{ name: "3", category: "Movies", region: "US" },
{ name: "4", category: "Music", region: "US" },
{ name: "5", category: "Movies", region: "UK" },
{ name: "6", category: "Movies", region: "UK" },
{ name: "6", category: "Cartoon", region: "SP" }
];
const filtrering = [
{ name: 'category', values: ['TV', 'Movies'] },
{ name: 'region', values: ['UK'] }
];

const output = arr.reduce((acc, curr) => {
let isNodeSatisfied = false;
filtrering.forEach((criteria) => {
isNodeSatisfied = isNodeSatisfied || criteria.values.indexOf(curr[criteria.name]) > -1;
})
if (isNodeSatisfied) {
acc.push(curr)
}
return acc;
}, []);
console.log(output);

Javascript JSON file filter with object as a parameter

You don't need destructuring, what you need is array filter.

You also forgot to set a default {} so you can access undefined keys:

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/filter

const data = [  { "id": 44, "hours": 100,"finished": false },  { "id": 22, "hours": 80,"finished": false },  { "id": 65, "hours": 34,"finished": false },  { "id": 1098, "hours": 21,"finished": true  },  { "id": 2, "hours": 67,"finished": false },  { "id": 765, "hours": 32,"finished": false },  { "id": 223, "hours": 555,"finished": false },  { "id": 986, "hours": 2,"finished": false },  { "id": 1986, "hours": 30,"finished": false },];
function dataFilter (items, {id: _id, hours: _hours, finished: _finished} = {}) { return items.filter((item) => item.id === _id || item.hours >= _hours || item.finished === _finished);}
document.getElementById('results').innerHTML = `<pre>ID: 65${JSON.stringify(dataFilter(data,{ id: 65 }), null, 2)} HOURS: 30${JSON.stringify(dataFilter(data,{ hours: 30 }), null, 2)}</pre>`
<div id="results"></div>


Related Topics



Leave a reply



Submit