How to filter JSON Data in JavaScript or jQuery?
This is how you should do it : ( for google find)
$([
{"name":"Lenovo Thinkpad 41A4298","website":"google222"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"}
])
.filter(function (i,n){
return n.website==='google';
});
Better solution : ( Salman's)
$.grep( [{"name":"Lenovo Thinkpad 41A4298","website":"google"},{"name":"Lenovo Thinkpad 41A2222","website":"google"}], function( n, i ) {
return n.website==='google';
});
http://jsbin.com/yakubixi/4/edit
Filter JSON by key value
You should use filter
method.
The filter()
method creates a new array
with all elements that pass the test implemented by the provided function.
Provided function is a callback
which is applied to each element of the array.
var arr = [{"time":"2016-07-26 09:02:27","type":"aa"}, {"time":"2016-04-21 20:35:07","type":"ae"}, {"time":"2016-08-20 03:31:57","type":"ar"}, {"time":"2017-01-19 22:58:06","type":"ae"}, {"time":"2016-08-28 10:19:27","type":"ae"}, {"time":"2016-12-06 10:36:22","type":"ar"}, {"time":"2016-07-09 12:14:03","type":"ar"}, {"time":"2016-10-25 05:05:37","type":"ae"}, {"time":"2016-06-05 07:57:18","type":"ae"}, {"time":"2016-10-08 22:03:03","type":"aa"}, {"time":"2016-08-13 21:27:37","type":"ae"}, {"time":"2016-04-09 07:36:16","type":"ar"}, {"time":"2016-12-30 17:20:08","type":"aa"}, {"time":"2016-03-11 17:31:46","type":"aa"}, {"time":"2016-05-04 14:08:25","type":"ar"}, {"time":"2016-11-29 05:21:02","type":"ar"}, {"time":"2016-03-08 05:46:01","type":"ar"}, ];
console.log(arr.filter(function(item){
return item.type == "ar";
}));
how to filter json data using jquery
You can use .map() to create new array of objects with only the relevant content in it.
The following creates a new array of objects - with just the displayName and the phone numbers array for each user.
var data = [{"id":"1","rawId":"1","displayName":"user name 1","name":{"familyName":"user","givenName":"name","formatted":"user name 1"},"nickname":null,"phoneNumbers":[{"id":"2","pref":false,"value":"9874563210","type":"other"}],"emails":null,"addresses":null,"ims":null,"organizations":null,"birthday":null,"note":null,"photos":null,"categories":null,"urls":"http://www.user1.com"},{"id":"2","rawId":"1","displayName":"user name 2","name":{"familyName":"user","givenName":"name","formatted":"user name 2"},"nickname":null,"phoneNumbers":[{"id":"2","pref":false,"value":"9632587410","type":"other"}],"emails":null,"addresses":null,"ims":null,"organizations":null,"birthday":null,"note":null,"photos":null,"categories":null,"urls":"http://www.yahoo.com"},{"id":"3","rawId":"1","displayName":"user name 3","name":{"familyName":"user","givenName":"name","formatted":"user name 3"},"nickname":null,"phoneNumbers":[{"id":"2","pref":false,"value":"9858745852","type":"other"}],"emails":null,"addresses":null,"ims":null,"organizations":null,"birthday":null,"note":null,"photos":null,"categories":null,"urls":null},{"id":"4","rawId":"1","displayName":"Distress Number","name":{"familyName":"Number","givenName":"Distress","formatted":"Distress Number"},"nickname":null,"phoneNumbers":[{"id":"2","pref":false,"value":"8547125693","type":"other"}],"emails":null,"addresses":null,"ims":null,"organizations":null,"birthday":null,"note":null,"photos":null,"categories":null,"urls":"http://www.goo.com"}]
let details = data.map(item => { return {displayName: item.displayName, phoneNumbers: item.phoneNumbers}})
console.log(details)
How can I filter a JSON object in JavaScript?
You can create a function using reduce()
and Object.keys()
that will check key names with indexOf()
and return the desired result.
var obj = {
"Alarm": {
"Hello": 48,
"World": 3,
"Orange": 1
},
"Rapid": {
"Total": 746084,
"Fake": 20970,
"Cancel": 9985,
"Word": 2343
},
"Flow": {
"Support": 746084,
"About": 0,
"Learn": 0
}
}
function filterBy(val) {
var result = Object.keys(obj).reduce(function(r, e) {
if (e.toLowerCase().indexOf(val) != -1) {
r[e] = obj[e];
} else {
Object.keys(obj[e]).forEach(function(k) {
if (k.toLowerCase().indexOf(val) != -1) {
var object = {}
object[k] = obj[e][k];
r[e] = object;
}
})
}
return r;
}, {})
return result;
}
console.log(filterBy('ange'))
console.log(filterBy('flo'))
console.log(filterBy('wor'))
Filter JSON Data with multiple filters in jQuery
This would work:
var filters = {Diesel: "1", CarWash: "Full"};
var facilities = [{ "FacilityID": 123, "Diesel": 0, "ATM": 0, "CarWash": "None" }, { "FacilityID": 456, "Diesel": 1, "ATM": 0, "CarWash": "None" }, { "FacilityID": 789, "Diesel": 1, "ATM": 0, "CarWash": "Full" } ];
var selectedFacility = null;
// loop over each facilities $.each(facilities, function(i, facility) { var matchesAllFilters = true; // loop over each filter $.each(filters, function(filterName, filterValue) { var facilityValue = facility[filterName]; if (filterValue != facilityValue) { matchesAllFilters = false; return false; } }); if (matchesAllFilters) { selectedFacility = facility; } });
console.log(selectedFacility );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Filter JSON data with jquery
You really do not need JQuery for this. You can use Object.values()
function to get an array of values for each property in the object:
const input = { "0":{ "name":"example", "age":"21" }, "1":{ "name":"example2", "age":"22" }}
const result = Object.values(input)
console.log(result)
Filter json based on key and match it against one of the values from array
Use Array.some()
to test if it starts with any of the strings in testMatch.match
.
const products = [{
"id": "1",
"category": "Fruit from USA",
"name": "Banana",
},
{
"id": "2",
"category": "Fruit from Brazil",
"name": "Long Banana",
},
{
"id": "3",
"category": "Vegetable",
"name": "Carrot",
},
{
"id": "4",
"category": "Car from USA",
"name": "Ford",
},
{
"id": "5",
"category": "Car from Germany",
"name": "Audi",
},
{
"id": "6",
"category": "Train from Italy",
"name": "Pendolino",
},
];
const testMatch = {
match: ['Car', 'Fruit']
};
const productList = products.filter(filteredCategory =>
testMatch.match.some(match => filteredCategory.category.startsWith(match)));
console.log(productList);
How to filter an json object by another object - Javascript
You can use every
and includes
to make a boolean value that will work with filter()
.
For example:
var jsondata = [{"firstName": "Sam","lastName": "Jones","age": "10"},{"firstName": "Sam1","lastName": "Jones1","age": "10"},{"firstName": "Sam2","lastName": "Jones2","age": "12"},{"firstName": "Sam3","lastName": "Jones3","age": "13"},{"firstName": "Sam4","lastName": "Jones4","age": "14"},{"firstName": "Sam5","lastName": "Jones5","age": "15"},{"firstName": "Sam","lastName": "Jones11","age": "16"},{"firstName": "Sam6","lastName": "Jones6","age": "17"},{"firstName": "Sam7","lastName": "Jones7","age": "18"},{"firstName": "Sam8","lastName": "Jones8","age": "19"},{"firstName": "Sam9","lastName": "Jones9","age": "20"},{"firstName": "Sam10","lastName": "Jones10","age": "21"},{"firstName": "Sam11","lastName": "Jones11","age": "22"},{"firstName": "Sam12","lastName": "Jones12","age": "23"}] var filterArray = [{"id":"firstName","value":["Sam"]},{"id":"lastName","value":["Jones"]}]
let filtered = jsondata.filter(item => // filter jsondata filterArray.every( f => // so every member of filter array f.value.includes(item[f.id])) ) // has a corresponding item[id] in value
console.log(filtered)
How to Filter a complex json object using javascript?
You can use Array#filter
and assign the result directly to the property HOMES
.
var json = { "Lofts": "none", "Maisons": "2", "HOMES": [{ "home_id": "1", "price": "925", "num_of_beds": "2" }, { "home_id": "2", "price": "1425", "num_of_beds": "4", }, { "home_id": "3", "price": "333", "num_of_beds": "5", }] };
json.HOMES = json.HOMES.filter(function (a) { return a.home_id === '2';});
document.write('<pre>' + JSON.stringify(json, 0, 4) + '</pre>');
Related Topics
How to Rotate a 3D Object on Axis Three.Js
Getting Key with the Highest Value from Object
JavaScript Change Date into Format of (Dd/Mm/Yyyy)
Is There Any Difference Between Declared and Defined Variable
How to Animate Scrolltop with Jquery
Can You Do Desktop Development Using JavaScript
How to Shuffle the Characters in a String in JavaScript
How to Inherit Old-Style Class from Ecmascript 6 Class in JavaScript
How to Disable JavaScript in Chrome Developer Tools
Eslint Parsing Error: Unexpected Token
Regex for Match/Replacing JavaScript Comments (Both Multiline and Inline)
How to Check If a Number Is Between Two Values
How to Remove the Decimal Part from JavaScript Number
Extending Built-In Natives in Es6 with Babel
How to Stop a JavaScript for Loop
Jquery Difference Between Change and Click Event of Checkbox