Hello i want to filter json data like sql query without the help of plugins like alasql.js or linq.js or any plugins.
for example
{
"Managing PCL": [
{
"idItScreen": "1436",
"topicName": "Managing PCL",
"isFav": 0,
"cdeItScreen": "ListActiveTarif",
"busScreenName": "My Current Tarif"
},
{
"idItScreen": "1437",
"topicName": "Managing PCL",
"isFav": 0,
"cdeItScreen": "ListTermineTarif",
"busScreenName": "History Tarif"
}
]
}
for example i need to get data where idItScreen>1430 so that json data must be displayed the main challenge is to do without plugins so please reccomend me a good solution to do this without plugins
First turn your JSON into a Javascript object:
var obj = JSON.parse(myJSON);
Then do your filtering:
var matches = [];
var arr = obj['Managing PCL'];
for (var i = 0; i < arr.length; i++) {
if (arr[i].idItScreen > 1430) {
matches.push(arr[i]);
}
}
Or using jQuery.grep:
var matches = jQuery.grep(obj['Managing PCL'], function(n, i) {
return n.idItScreen > 1430;
});
Now matches contains the matching items.
If you want to get the JSON again, just use JSON.stringify:
var filteredJSON = JSON.stringify({'Managing PCL': matches});
You can also simply use .filter:
var matches = [];
var all = obj['Managing PCL'];
var filtered = all.filter(function(){
return $(this).idItScreen > 1430;
})
You don't need to use jQuery for this. You can use the filter() method of Array.prototype. See the working snippet below:
var obj = {
"Managing PCL": [{
"idItScreen": "1436",
"topicName": "Managing PCL",
"isFav": 0,
"cdeItScreen": "ListActiveTarif",
"busScreenName": "My Current Tarif"
}, {
"idItScreen": "1437",
"topicName": "Managing PCL",
"isFav": 0,
"cdeItScreen": "ListTermineTarif",
"busScreenName": "History Tarif"
}]
};
var filteredArray = obj['Managing PCL'].filter(function(item) {
return item.idItScreen > 1430;
});
obj['Managing PCL'] = filteredArray;
document.getElementById('result').innerHTML = JSON.stringify(obj);
<div id="result"></div>
You don't need jQuery for this. Use filter on the data instead.
function filterData(data, key, value) {
return data.filter(function (el) {
return el[key] > value;
});
}
// Note, `filter` operates on arrays, so you need to specify the
// array that contains the data
var result = filterData(data['Managing PCL'], 'idItScreen', '1430');
Also note that filter returns a new array containing the objects that it's found that match your criteria. You can access those objects in the usual way: result[0], for example.
DEMO
You could even expand this to create a function that returns data based on the operator too, not just greater-than, by using a look-up object:
var lookup = {
'>': function (data, value) { return data > value; },
'<': function (data, value) { return data < value; },
'===': function (data, value) { return data === value; }
}
function filterData(data, key, operator, value) {
return data.filter(function (el) {
return lookup[operator](el[key], value);
});
}
filterData(data['Managing PCL'], 'idItScreen', '>', '1430');
filterData(data['Managing PCL'], 'idItScreen', '===', '1430');
DEMO
Related
I have the below JSON string. The id-dashes in the file are not optional unfortunately, neither is the syntax. I would like to extract the "dd" values with JavaScript/Node.
{
"a-id":{
"b-id":"random",
"bb-id":"random",
"bbb-id":"random",
"bbbb-id":{
"c":[
{
"d":"random",
"dd":"This_info_is_needed"
},
{
"d":"random",
"dd":"This_info_is_needed"
},
{
"d":"random",
"dd":"This_info_is_needed"
},
{
"d":"random",
"dd":"This_info_is_needed_2"
}
]
},
"bbbbb-id":"random",
"bbbbbb-id":"random"
}
}
I would be open to use any additional helper like lodash, jQuery, etc.
The output should be an array with: This_info_is_needed and This_info_is_needed_2.
Thank you in advance.
You can create custom function that will search your data deep and return value if key is dd using for...in loop.
var obj = {"a-id":{"b-id":"random","bb-id":"random","bbb-id":"random","bbbb-id":{"c":[{"d":"random","dd":"This_info_is_needed"},{"d":"random","dd":"This_info_is_needed"},{"d":"random","dd":"This_info_is_needed"},{"d":"random","dd":"This_info_is_needed"}]},"bbbbb-id":"random","bbbbbb-id":"random"}}
function getDD(data) {
var result = []
for(var i in data) {
if(i == 'dd') result.push(data[i])
if(typeof data[i] == 'object') result.push(...getDD(data[i]))
}
return result
}
console.log(getDD(obj))
If you just interested in the values only, can also just do this:
var obj = {"a-id":{"b-id":"random","bb-id":"random","bbb-id":"random","bbbb-id":{"c":[{"d":"random","dd":"This_info_is_needed"},{"d":"random","dd":"This_info_is_needed"},{"d":"random","dd":"This_info_is_needed"},{"d":"random","dd":"This_info_is_needed"}]},"bbbbb-id":"random","bbbbbb-id":"random"}};
var desiredResults = obj['a-id']['bbbb-id']['c'].map(function(data){return data.dd});
console.log(desiredResults);
I need your help,
Id' like to be able to come up with a javascript function that is similar to the following code structure below, except for the fact that I am not that strong enough in programming to come up with a workable solution to work from.
I'd like to be able to input a given value, then, using that value, search through an array and return the value short name (the value on the right side of the : colon character)
function test() {
var filenames = [
"REQUEST FOR INFO":"REQI",
"MEDIA CALL":"MC",
"ISSUES NOTE":"ISN"
]
EX1.)
var value_to_search_for = "REQUEST FOR INFO (ALPHA)"
if (value_to_search_for matches the value in the array filenames) then {
return "REQI"
}
EX.2)
var value_to_search_for = "MEDIA CALL"
if (value_to_search_for matches value in the array filenames) then {
return "MC"
}
}
You can change that to object and then you can do this
var filenames = {
"REQUEST FOR INFO": "REQI",
"MEDIA CALL": "MC",
"ISSUES NOTE": "ISN"
};
var getValue = function(val, obj) {
if (val in obj) return obj[val];
}
console.log(getValue('ISSUES NOTE', filenames));
You can also change that to array of objects and then you can do this
var filenames = [
{"REQUEST FOR INFO": "REQI"},
{"MEDIA CALL": "MC"},
{"ISSUES NOTE": "ISN"}
];
var getValue = function(val, array) {
array.forEach(function(el) {
for (prop in el) {
if (prop == val) console.log(el[prop]);
}
});
}
getValue('MEDIA CALL', filenames);
I wish to search on multiple columns however all the code I could find on the internet was restricted on a single search term that would search multiple columns. I wish to filter on multiple columns by multiple search terms
data:
var propertynames = ['firstName','lastName'];
var data = [
{
"city":"Irwin town",
"address":"1399 Cecil Drive",
"lastName":"Auer",
"firstName":"Wanda"
},
{
"city":"Howell haven"
"address":"168 Arnoldo Light"
"lastName":"Balistreri",
"firstName":"Renee"
}
];
var searchTerm = 'Wanda Auer';
Should result in an array that filtered out the 2nd object.
Thanks!
I've created two solutions for your question. The first one is do exactly what you need: filters collection by two fields. The second one is more flexible, because it allows filter by any multiple fields.
First solution:
function filterByTwoFields(coll, searchFilter) {
return _.filter(coll, function(item) {
return (item.firstName + ' ' + item.lastName) === searchTerm;
});
}
var data = [
{
"city":"Irwin town",
"address":"1399 Cecil Drive",
"lastName":"Auer",
"firstName":"Wanda"
},
{
"city":"Howell haven",
"address":"168 Arnoldo Light",
"lastName":"Balistreri",
"firstName":"Renee"
}
];
var searchTerm = 'Wanda Auer';
var result = filterByTwoFields(data, searchTerm);
alert(JSON.stringify(result));
<script src="https://raw.githubusercontent.com/lodash/lodash/master/dist/lodash.min.js"></script>
Second solution:
function filterByMultipleFields(coll, filter) {
var filterKeys = _.keys(filter);
return _.filter(coll, function(item) {
return _.every(filterKeys, function(key) {
return item[key] === filter[key];
});
});
}
var data = [
{
"city":"Irwin town",
"address":"1399 Cecil Drive",
"lastName":"Auer",
"firstName":"Wanda"
},
{
"city":"Howell haven",
"address":"168 Arnoldo Light",
"lastName":"Balistreri",
"firstName":"Renee"
}
];
var filter = {
firstName: 'Wanda',
lastName: 'Auer'
}
var result = filterByMultipleFields(data, filter);
alert(JSON.stringify(result));
<script src="https://raw.githubusercontent.com/lodash/lodash/master/dist/lodash.min.js"></script>
Not the most efficent but it does the job. You might want to make an non case sensitive comparison on the property values:
var searchTerm = 'Wanda Auer',
splitted = searchTerm.split(' ');
var result = data.filter(function(item){
return window.Object.keys(item).some(function(prop){
if(propertynames.indexOf(prop) === -1)
return;
return splitted.some(function(term){
return item[prop] === term;
});
});
});
https://jsfiddle.net/3g626fb8/1/
Edit: Just noticed the Lodash tag. If you want to use it, the framework is using the same function names as the array prototype, i.e. _.filter and _.some
Here is a pretty straightforward lodash version:
var matchingRecords = _.filter(data, function (object) {
return _(object)
.pick(propertynames)
.values()
.intersection(searchTerm.split(' '))
.size() > 0;
})
It filters the objects based on if any of the chosen property name values intersect with the search term tokens.
I have the following JSON -
{
"node1":[
{
"one":"foo",
"two":"foo",
"three":"foo",
"four":"foo"
},
{
"one":"bar",
"two":"bar",
"three":"bar",
"four":"bar"
},
{
"one":"foo",
"two":"foo",
"three":"foo",
"four":"foo"
}
],
"node2":[
{
"link":"baz",
"link2":"baz"
},
{
"link":"baz",
"link2":"baz"
},
{
"link":"qux",
"link2":"qux"
},
]
};
I have the following javascript that will remove duplicates from the node1 section -
function groupBy(items, propertyName) {
var result = [];
$.each(items, function (index, item) {
if ($.inArray(item[propertyName], result) == -1) {
result.push(item[propertyName]);
}
});
return result;
}
groupBy(catalog.node1, 'one');
However this does not account for dupicates in node2.
The resulting JSON I require is to look like -
{
"node1":[
{
"one":"foo",
"two":"foo",
"three":"foo",
"four":"foo"
},
{
"one":"bar",
"two":"bar",
"three":"bar",
"four":"bar"
}
],
"node2":[
{
"link":"baz",
"link2":"baz"
},
{
"link":"qux",
"link2":"qux"
},
]
};
However I cannot get this to work and groupBy only returns a string with the duplicates removed not a restructured JSON?
You should probably look for some good implementation of a JavaScript set and use that to represent your node objects. The set data structure would ensure that you only keep unique items.
On the other hand, you may try to write your own dedup algorithm. This is one example
function dedup(data, equals){
if(data.length > 1){
return data.reduce(function(set, item){
var alreadyExist = set.some(function(unique){
return equals(unique, item);
});
if(!alreadyExist){
set.push(item)
}
return set;
},[]);
}
return [].concat(data);
}
Unfortunately, the performance of this algorithm is not too good, I think somewhat like O(n^2/2) since I check the set of unique items every time to verify if a given item exists. This won't be a big deal if your structure is really that small. But at any rate, this is where a hash-based or a tree-based algorithm would probably be better.
You can also see that I have abstracted away the definition of what is "equal". So you can provide that in a secondary function. Most likely the use of JSON.stringify is a bad idea because it takes time to serialize an object. If you can write your own customized algorithm to compare key by key that'd be probably better.
So, a naive (not recommended) implementation of equals could be somewhat like the proposed in the other answer:
var equals = function(left, right){
return JSON.stringify(left) === JSON.stringify(right);
};
And then you could simply do:
var res = Object.keys(source).reduce(function(res, key){
res[key] = dedup(source[key], equals);
return res;
},{});
Here is my version:
var obj = {} // JSON object provided in the post.
var result = Object.keys(obj);
var test = result.map(function(o){
obj[o] = obj[o].reduce(function(a,c){
if (!a.some(function(item){
return JSON.stringify(item) === JSON.stringify(c); })){
a.push(c);
}
return a;
},[]); return obj[o]; });
console.log(obj);//outputs the expected result
Using Array.prototype.reduce along with Array.prototype.some I searched for all the items being added into the new array generated into Array.prototype.reduce in the var named a by doing:
a.some(function(item){ return JSON.stringify(item) === JSON.stringify(c); })
Array.prototype.some will loop trough this new array and compare the existing items against the new item c using JSON.stringify.
Try this:
var duplicatedDataArray = [];
var DuplicatedArray = [];
//Avoiding Duplicate in Array Datas
var givenData = {givenDataForDuplication : givenArray};
$.each(givenData.givenDataForDuplication, function (index, value) {
if ($.inArray(value.ItemName, duplicatedDataArray) == -1) {
duplicatedDataArray.push(value.ItemName);
DuplicatedArray.push(value);
}
});
I've got a jquery json request and in that json data I want to be able to sort by unique values. so I have
{
"people": [{
"pbid": "626",
"birthDate": "1976-02-06",
"name": 'name'
}, {
"pbid": "648",
"birthDate": "1987-05-22",
"name": 'name'
}, .....
So, far, i have this
function(data) {
$.each(data.people, function(i, person) {
alert(person.birthDate);
})
}
but, I am at a total loss as to how efficiently get only the unique birthDates, and sort them by year (or any sort by any other personal data).
I'm trying to do this, and be efficient about it (i'm hoping that is possible).
Thanks
I'm not sure how performant this will be, but basically I'm using an object as a key/value dictionary. I haven't tested this, but this should be sorted in the loop.
function(data) {
var birthDates = {};
var param = "birthDate"
$.each(data.people, function() {
if (!birthDates[this[param]])
birthDates[this[param]] = [];
birthDates[this[param]].push(this);
});
for(var d in birthDates) {
// add d to array here
// or do something with d
// birthDates[d] is the array of people
}
}
function(data){
var arr = new Array();
$.each(data.people, function(i, person){
if (jQuery.inArray(person.birthDate, arr) === -1) {
alert(person.birthDate);
arr.push(person.birthDate);
}
});
}
Here's my take:
function getUniqueBirthdays(data){
var birthdays = [];
$.each(data.people, function(){
if ($.inArray(this.birthDate,birthdays) === -1) {
birthdays.push(this.birthDate);
}
});
return birthdays.sort();
}