how to get distinct values from json in jquery - javascript

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

Related

Extract values from JSON

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

Json Filtering in jquery

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

refactor two $.each() loops to one

I have a JSON object like this...
{
"tasks":[
{
"id":"task_3",
"taskName":"Task A",
"assignee":"Barrack Obama",
"timeReqOptimisitic":"4",
"timeReqNormal":"8",
"timeReqPessimistic":"14",
"timeUnit":"Days",
"timeReq":"8.33",
"positionX":493,
"positionY":101,
"lockStatus":"unlocked"
}
],
"milestones":[
{
"id":"task_1",
"milestoneName":"Start",
"positionX":149,
"positionY":109,
"lockStatus":"unlocked",
"milestoneDate":"2015-04-07"
},
{
"id":"task_2",
"milestoneName":"Finish",
"positionX":989,
"positionY":367,
"lockStatus":"unlocked",
"milestoneDate":"2015-04-22"
}
],
"connections":[
{
"connectionId":"con_10",
"pageSourceId":"task_1",
"pageTargetId":"task_3"
},
{
"connectionId":"con_20",
"pageSourceId":"task_3",
"pageTargetId":"task_2"
}
]
}
...this is a minimal version. In practice, there are numerous items in "tasks", "milestones" and "connections".
I need to iterate through the object and determine the "id" of the "milestones" item with the lowest/earliest "milestoneDate", then identify the "connections" item that has the same value for its "pageSourceId" and return its "pageTargetId".
So in the above example:
Step 1) Iterate through the object and determine the "id" of the "milestones" item with the lowest/earliest "milestoneDate".
Answer: milestones.id = "task_1"
Step 2) Identify the "connections" item that has the same value for its "pageSourceId".
Answer: connections.pageSourceId = "task_1"
Step 3) Return its "pageTargetId".
Answer: "task_3"
I have a working example here. However, I would like to know if there is a way to accomplish this without using the extremely high start date and also in one loop.
As you are not parsing the same array on these two loops, there is no way to merge your loops.
Anyway, you can yet remove the loops to access to the arrays:
http://jsfiddle.net/gael/sruvtwre/2/
$.each(object.milestones, function( index, value ) {
if(startDate > parseDate(value.milestoneDate)) {
startDate = parseDate(value.milestoneDate);
id = value.id
}
});
$.each(object.connections, function( index, value ) {
if(id == value.pageSourceId) {
pageTargetId = value.pageTargetId;
}
});
May be also sorting, and indexing your datas. Then you would need no loops:
Elements in milestones should be sorted, so the earliest milestones element would be milestones[0].
Elements in connections should be indexed by their pageTargetId property, so the requested element should be connections[id].
Your two loops would become:
var pageTargetId= object.connections[ object.milestones[0].id ].pageTargetId;
http://jsfiddle.net/gael/sruvtwre/4/
As said in comments, sorting is not an optimal solution, even if that does not really matter for small sets.
Roughly, there is no no needs to sort all the datas, just the latest matters.
You can use array reduce method, as an comparable alternative to a simple loop:
var latestMilestone= object.milestones.reduce(function(milestone1, milestone2){
if( parseDate(milestone1.milestoneDate) > parseDate(milestone2.milestoneDate) )
return milestone1;
else
return milestone2;
//convert date to timestamp
function parseDate(date) {
var parts = date.split('-');
return Date.UTC(parts[0], parts[1]-1, parts[2]); // Note: months are 0-based
}
});
How about this:
Assuming you get the milestones.id = "task_1" in first loop; outside the loop we can have use jQuery grep. As connections will have unique pageSourceId, grep will return an array with only one object.
var filteredData = jQuery.grep('CONNECTIONS_ARRAY', function(element, index){
return element.pageSourceId == 'MILESTONES_ID'; // Which you get in the loop earlier
});
Then we can access pageTargetId like this:
if(filteredData.length){
filteredData[0].pageTargetId;
}
Try
var dates = []
, ids = []
, filtered = $.map(data.milestones, function(value, index) {
dates.push(new Date(value.milestoneDate).getTime());
ids.push(value.id);
if (dates.length === data.milestones.length) {
var id = ids[$.inArray(Math.min.apply(Math, dates), dates)]
, res = $.grep(data.connections, function(task, key) {
return task.pageSourceId === id
})[0].pageTargetId;
return res
}
})[0]; // `"task_3"`
var data = {
"tasks":[
{
"id":"task_3",
"taskName":"Task A",
"assignee":"Barrack Obama",
"timeReqOptimisitic":"4",
"timeReqNormal":"8",
"timeReqPessimistic":"14",
"timeUnit":"Days",
"timeReq":"8.33",
"positionX":493,
"positionY":101,
"lockStatus":"unlocked"
}
],
"milestones":[
{
"id":"task_1",
"milestoneName":"Start",
"positionX":149,
"positionY":109,
"lockStatus":"unlocked",
"milestoneDate":"2015-04-07"
},
{
"id":"task_2",
"milestoneName":"Finish",
"positionX":989,
"positionY":367,
"lockStatus":"unlocked",
"milestoneDate":"2015-04-22"
}
],
"connections":[
{
"connectionId":"con_10",
"pageSourceId":"task_1",
"pageTargetId":"task_3"
},
{
"connectionId":"con_20",
"pageSourceId":"task_3",
"pageTargetId":"task_2"
}
]
};
var dates = []
, ids = []
, filtered = $.map(data.milestones, function(value, index) {
dates.push(new Date(value.milestoneDate).getTime());
ids.push(value.id);
if (dates.length === data.milestones.length) {
var id = ids[$.inArray(Math.min.apply(Math, dates), dates)]
, res = $.grep(data.connections, function(task, key) {
return task.pageSourceId === id
})[0].pageTargetId;
return res
}
})[0];
document.write(filtered);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

Reconstruct JSON after duplicates have been removed

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

Finding object in nested collection with Underscore.js

I have a collection of teams (in a league) like so:
var fra1 = {
"sports":[
{
"name":"soccer",
"id":600,
"uid":"s:600",
"leagues":[
{
"name":"French Ligue 1",
"abbreviation":"fra.1",
"id":710,
"isTournament":false,
"country":{
"id":7,
"name":"France",
"abbreviation":"FRA"
},
"uid":"s:600~l:710",
"groupId":9,
"shortName":"Ligue 1",
"teams":[
{
"id":159,
"uid":"s:600~t:159",
"location":"Bordeaux",
"name":"Bordeaux",
"nickname":"Bordeaux",
"abbreviation":"BOR",
"color":"00003e",
},
{
"id":160,
"uid":"s:600~t:160",
"location":"Paris Saint-Germain ",
"name":"Paris Saint-Germain ",
"nickname":"Paris Saint-Germain ",
"abbreviation":"PSG",
"color":"000040",
}
]
}
]
}
],
}
There are about 20 teams in each var stored in this way. Then, I have about six such leagues: eng1, esp1, fra1, ger1, ita1, and usa1. I put those in another collection, like so:
var all = {
"eng1":eng1,
"esp1":esp1,
"fra1":fra1,
"ger1":ger1,
"ita1":ita1,
"usa1":usa1
}
Now, each team (regardless of the league they're in) has a unique ID: in the above example, Bordeaux has ID 159, PSG has ID 160, and so on. So I want to be able to search the all collection for a unique team by teamid, using Underscore.js, but I can't quite get the syntax down. I know I could search one league like so:
var obj = _.find(fra1.sports[0].leagues[0].teams, function(obj) { return obj.id == teamid })
But I can't figure out how to do it across all six leagues. Can anyone help? I'd prefer not to have to combine the collections into one manually, that would be cumbersome with the amount of data involved.
EDIT: I'm currently using:
for (var league in all)
{
var obj = _.find(all[league].sports[0].leagues[0].teams, function(obj) { return obj.id == teamid })
if (obj !== undefined)
{
// do things
}
}
But would still like something nicer.
One solution would be to create a map of the teams with the team id as the key and the team as the value:
var teams = {};
_.each(all, function(nation){
_.each(nation.sports[0].leagues[0].teams, function(team){
teams[team.id] = team;
});
});
You could then access the team using the key:
var psg = teams[160];
As far as parsing the rest of the teams, just use chain:
var allTeams = _.chain(all)
.values()
.pluck('sports').flatten() // once
.pluck('leagues').flatten() // twice
.pluck('teams').flatten() // third time's a charm
.value()
I would recommend using _.groupBy() on teamID. This will give you a hash-table (JS object) that maps teamID -> teamObject. Say you have your teams parsed like this:
var allTeams =[
{
"id":159,
"uid":"s:600~t:159",
"location":"Bordeaux",
"name":"Bordeaux",
"nickname":"Bordeaux",
"abbreviation":"BOR",
"color":"00003e",
},{
"id":160,
"uid":"s:600~t:160",
"location":"Paris Saint-Germain ",
"name":"Paris Saint-Germain ",
"nickname":"Paris Saint-Germain ",
"abbreviation":"PSG",
"color":"000040",
}]
You can group them with:
var lookup = _.groupBy(teams, 'id')
And then look up a team like this:
var myTeam = lookup[teamId]
Simply do additional loops over the sports and leagues, not only over all:
for (var league in all) {
var sports = all[league];
for (var i=0; i<sports.length; i++) {
var leagues = sports[i].leagues;
for (var j=0; j<leagues.length; j++) {
var teams = leagues[j].teams;
// var obj = _.find(teams, function(obj) { return obj.id == teamid })
for (var k=0; k<teams.length; k++) {
var obj = teams[k];
if (obj.id == teamid) {
… // do things
}
}
}
}
}

Categories