extract part of json into another object and keep link between both - javascript

{
   "data": [
      {
         "date": "2013-03-07",
         "id": "2",
         "vt_color": "#548dd4",
         "vt_name": "follow up",
         "duration": "20",
         "time_booked": "12:00:00",
         "stats": "booked",
         "doctor_id": "00002",
         "patient_id": "00003"
      },
      {
         "date": "2013-03-08",
         "id": "3",
         "vt_color": "#76923c",
         "vt_name": "ultrasound",
         "duration": "30",
         "time_booked": "08:00:00",
         "stats": "booked",
         "pt_name": "demo patien",
         "dr_name": "Momen Alzalabany",
         "doctor_id": "00002",
         "patient_id": "00009"
      }
   ] 
}
what i want is to create another array out of this including vt_name,vt_color and index of data
so i use jquery
var words = [];
$.each(arr['data'],function(ref){
words[this.doctor_id].push({name: this.vt_color,color: this.vt_name,index:ref});
});
console.log(koko);
FAIL : words[this.do_id] is not defined....
how can i do this ? i want outcome to be
sorry i'm a newbie with json/js
i want outcome in php would be
['00002'=>[
['name'=>'follow up','color'=>'#548dd4',index=>[0,3,4]],
['name'=>'ultrasound','color'=>'#769dd4',index=>[1,5,8]]
]
]

Change the type of words to object (not array), since you want a map with a string (e.g. '00002') as key:
var words = {};
You want do add to an array which does not exist. You need to create it first:
words[this.doctor_id] = words[this.doctor_id] || []; // creates an array if not already existing
words[this.doctor_id].push({name: this.vt_color,color: this.vt_name,index:ref});

Related

JSON Format is off

The keys and values are separated in the Json object that I get from an api call. I have tried finding a solution It looks like the following:
{
"range": "'1'!A1:AM243",
"majorDimension": "ROWS",
"values":
[
"DeptID",
"DeptDescr",
"VP Area",
"VP Descr",
"HR Category",
"Employee Relations1",
"ER1Title",
"ER1Phone",
"ER1Email",
"Employee Relations2",
"ER2Title",
"ER2Phone",
"ER2Email",
"Compensation1",
"Comp1Title",
"Comp1Phone",
"Comp1Email",
"Compensation2",
"Comp2Title",
"Comp2Phone",
"Comp2Email",
"Employment1",
"E1Title",
"E1Phone",
"E1Email",
"Employment2",
"E2Title",
"E2Phone",
"E2Email",
"Employee Pay Services1",
"EPS1Title",
"EPS1Phone",
"EPS1Email",
"Employee Pay Services2",
"EPS2Title",
"EPS2Phone",
"EPS2Email"
],
[
"20734",
"Academic Success Centers",
"VES",
"VP Enroll Mgmt & Student Aff",
"Administrative",
"Brian Schmidt",
" Employee Relations Consultant",
"(928)523-6139",
"Brian.Schmidt#nau.edu",
"Marcia Warden",
"Assistant Director, Employee Relations",
"(928)523-9624",
"Marcia.Warden#nau.edu",
"Nicole Christian",
"Employment & Compensation Analyst",
"(928)523-6127",
" Nicole.Christian#nau.edu",
"Cathy Speirs",
"Associate Director",
"(928)523-6136",
"Cathy.Speirs#nau.edu",
"Nicole Christian",
"Employment & Compensation Analyst",
"(928)523-6127",
" Nicole.Christian#nau.edu",
"Cathy Speirs",
"Associate Director",
"(928)523-6136",
"Cathy.Speirs#nau.edu",
"Katherine Kurpierz",
"Payroll Specialist",
"(928)523-6129",
"Katherine.Kurpierz#nau.edu",
"Cheryl Brothers",
"Assistant Director - HR Payroll Services",
"(928)523-6085",
"Cheryl.Brothers#nau.edu"
], etc.
But I need it to look like:
[
{
"DeptID": 20734,
"DeptDescr": "Academic Success Centers",
"VP Area": "VES",
"VP Descr": "VP Enroll Mgmt & Student Aff",
"HR Category": "Administrative",
"Employee Relations1": "Brian Schmidt",
"Employee Relations2": "Marcia Warden",
"Compensation1": "Nicole Christian",
"Compensation2": "Cathy Speirs",
"Employment1": "Nicole Christian",
"Employment3": "Cathy Speirs",
"Employee Pay Services1": "Katherine Kurpierz",
"Employee Pay Services2": "Cheryl Brothers"
},etc
I am trying to use the data to populate a drop down using javascript and ajax. Any help is really appreciated.
The object your API returns is not a valid JSON. Was that API made by you or can you get that fixed somehow?
There are 2 things you could do to make it work
-One is change it to return exactly what you want;
-Two is to fix what it returns so that it is a valid JSON;
Going for what is wrong with the file you initially posted, let's remove the contents of the arrays so it's easier to spot the problem:
Your original data looks roughly like this:
{ "range": "'1'!A1:AM243",
"majorDimension": "ROWS",
"values": [],[]
}
To be valid you would need it to look like this:
{ "range": "'1'!A1:AM243",
"majorDimension": "ROWS",
"values": {
"keys": [],
"data": [],
}
}
Notice that I wrapped the two arrays of "values" with { } because it has to be an object if you want it to contain two arrays in it.
Then I gave each array a key with which you can call them. With that you'd be able to get what you want from your "values", so that for each item in the "keys" array you have something in that "data" array.
Hope this helps.
Well let's have a look;
Suppose this is a short version of the response data you got:
var res = `
{
"range": "'1'!A1:AM243",
"majorDimension": "ROWS",
"values": [
"DeptID",
"DeptDescr",
"VP Area"
],
[
"20734",
"Academic Success Centers",
"VES"
],
[
"345543",
"Academic Fails Centers",
"OK"
]
}
`;
As we can see by the first data, looks like a dump from a spreadsheet of sorts, and someone maybe scripted a way to export this data in a JSON-ish way. The values "Array" are the rows of this "spreadsheet".
We will clean it up, and get only the chunks that looks like ["value", "another value", "etc"]
// clean tabs and returns
res = res.replace(/\t/g, '').replace(/\n/g, '');
// get the array-ish chunks
rows = res.match(/\[(((["'])(?:(?=(\\?))\4.)*?\3),*)+\]/gm)
now let's make them real arrays:
var data = rows.map(function (row) {
return JSON.parse(row);
});
Now we have an array of arrays of strings. that means, an array of "rows" that contains the values of the "cells". The first one looks like the header row (the one with the names of the fields)
Lets make objects using each row of data except the first one. The first will serve us as the keys (we match the position (index) of the value from rows[n] from the value on rows[0] to get a key-value pair)
// Here we will define an object to store data
var data_object = { values: [] };
// for each row except the first
for(var i = 1; i < data.length; i++) {
var my_data = {};
//for each element of this row
for(var j = 0; j < data[i].length; j++) {
my_data[data[0][j]] = data[i][j];
}
data_object.values.push(my_data);
}
We have our object, let's suppose you need it in JSON format now:
var json_data = JSON.stringify(data_object);
// let's look what we have here
console.log('json_data:', json_data);
We will look at something like this as a result:
json_data: {"values":[{"DeptID":"20734","DeptDescr":"Academic Success Centers","VP Area":"VES"},{"DeptID":"345543","DeptDescr":"Academic Fails Centers","VP Area":"OK"}]}
NOW A WARNING:
This is what you DON'T want to do if you can fix the API you are getting this data from first. If any inconsistency appears, things will break. and in this example i'm not managing any edge case or exception, neither checking boundaries of arrays or wrapping things in try-catch blocks.

Editing an object in nested data structure

I have a data structure like this:
var fieldTmp= [{
"CountryDetails":[{
"countryName":"Kerala",
"JobDetails":[{
"RequisitionId":"00020447961",
"City":"KOCHI",
"PostedDate":"2016-12-18"
},{
"RequisitionId":"26103",
"City":"TRIVANDRUM",
"PostedDate":"2016-12-12"
},{
"RequisitionId":"26077",
"City":"ALAPPEY",
"PostedDate":"2016-10-09"
},{
"RequisitionId":"00020774701",
"City":"KOTTAYAM",
"PostedDate":"2016-06-12"
},{
"RequisitionId":"26078",
"City":"ADOOR",
"PostedDate":"2016-05-19"}]
},
"countryName":"MADRAS",
"JobDetails":[{
"RequisitionId":"0025456",
"City":"CHENNAI",
"PostedDate":"2017-06-05"
},{
"RequisitionId":"69847562",
"City":"ADYAR",
"PostedDate":"2016-10-14"}]
},
{"countryName":"Tamil Nadu",
"JobDetails":[{
"RequisitionId":"00020550501",
"City":"CHENNAI",
"PostedDate":"2016-12-18"
},{
"RequisitionId":"00020786022",
"City":"KOVAI",
"PostedDate":"2016-09-01"
},{
"RequisitionId":"00020786071",
"City":"TRICHY",
"PostedDate":"2016-04-10"}]
}] }]
My requirement is, I need to add Job Details under MADRAS to Tamil Nadu and I need to sort the data based on one property -PostedDate.
So my result should be something like,
var fieldTmp= [{
"CountryDetails":[{
"countryName":"Kerala",
"JobDetails":[{
"RequisitionId":"00020447961",
"City":"KOCHI",
"PostedDate":"2016-12-18"
},{
"RequisitionId":"26103",
"City":"TRIVANDRUM",
"PostedDate":"2016-12-12"
},{
"RequisitionId":"26077",
"City":"ALAPPEY",
"PostedDate":"2016-10-09"
},{
"RequisitionId":"00020774701",
"City":"KOTTAYAM",
"PostedDate":"2016-06-12"
},{
"RequisitionId":"26078",
"City":"ADOOR",
"PostedDate":"2016-05-19"}]
},
{"countryName":"Tamil Nadu",
"JobDetails":[{
"RequisitionId":"0025456",
"City":"CHENNAI",
"PostedDate":"2017-06-05"
},{
"RequisitionId":"00020550501",
"City":"CHENNAI",
"PostedDate":"2016-12-18"
},{
"RequisitionId":"69847562",
"City":"ADYAR",
"PostedDate":"2016-10-14"
},{
"RequisitionId":"00020786022",
"City":"KOVAI",
"PostedDate":"2016-09-01"
},{
"RequisitionId":"00020786071",
"City":"TRICHY",
"PostedDate":"2016-04-10"}]
}] }]
I tried to extract Madras data and add that to under Tamil Nadu. But nothing is working.
I know how to extract single or multiple value from JSON object. But I need to edit that JSON and sort it. That I am able to do it.
I got the solution.
When the countryName is "Tamil Nadu" and "MADRAS",I extracted all the data and saved it in a new array using below code.
function mergingBothStateDetails(jsonJobDetails){
for(var j=0;j<jsonJobDetails.length;j++)
{
newTmpRecord.push({"RequisitionId":jsonJobDetails[j].RequisitionId,
"PostedDate":jsonJobDetails[j].PostedDate,
"City":jsonJobDetails[j].City});
}
}
Here newTmpRecord is an Array and is like universal variable
For sorting I used below codes
function sortNewList(){
newTmpRecord.sort(function(a, b){ // sort object by retirement date
var dateA=new Date(a.PostedDate), dateB=new Date(b.PostedDate)
return dateB-dateA //sort by date descending
});
}
You can simply extract the object "Madras" from the array and add all of its Jobdetails to the object "Tamil Nadu" in a for loop. You can either look where to add them in the loop by checking the dates, or you can write a sort function, which is pretty easy in javascript and well explained here:
You might want to look up objects
And here the sorting is explained.

JSON list optimization

I want to create a JSON API that returns a list of objects. Each object has an id, a name and some other information. API is consumed using JavaScript.
The natural options for my JSON output seems to be:
"myList": [
{
"id": 1,
"name": "object1",
"details": {}
},
{
"id": 2,
"name": "object2",
"details": {}
},
{
"id": 3,
"name": "object3",
"details": {}
},
]
Now let's imagine that I use my API to get all the objects but want to first do something with id2 then something else with id1 and id3.
Then I may be interested to be able to directly get the object for a specific id:
"myList": {
"1": {
"name": "object1",
"details": {}
},
"2": {
"name": "object2",
"details": {}
},
"3": {
"name": "object3",
"details": {}
},
}
This second option may be less natural when somewhere else in the code I want to simply loop through all the elements.
Is there a good practice for these use cases when the API is used for both looping through all elements and sometime using specific elements only (without doing a dedicated call for each element)?
In your example you've changed the ID value from 1 to id1. This would make operating on the data a bit annoying, because you have to add and remove id all the time.
If you didn't do that, and you were relying on the sorted order of the object, you may be in for a surprise, depending on JS engine:
var source = JSON.stringify({z: "first", a: "second", 0: "third"});
var parsed = JSON.parse(source);
console.log(Object.keys(parsed));
// ["0", "z", "a"]
My experience is to work with arrays on the transport layer and index the data (i.e. convert array to map) when required.

Keep the sort order

I have a object with that values :
category_list = {
"1000":{
"name":"Cars",
"order":"1",
"level": "2"
},
"2010":{
"name":"Houses",
"order":"2",
"level": "2"
},
"1030":{
"name":"Cars",
"order":"3",
"level": "2"
}
}
And when I would like to show it Chrome reorders it based on the Index :
It becomes :
category_list = {
"1000":{
"name":"Cars",
"order":"1",
"level": "2"
},
"1030":{
"name":"Cars",
"order":"3",
"level": "2"
},
"2010":{
"name":"Houses",
"order":"2",
"level": "2"
}
}
I wish to keep the order as it was when pushing! or reorder based on field "order"
Can someone please help with that?
JavaScript objects are by definition unordered.
If you need an ordered list, you should use an array (of objects) instead, e.g.:
var objs = [
{
"key": 1000,
"name":"Cars",
"order": 1,
"level": 2
}, ...
];
objs.sort(function(a, b) {
return a.order - b.order;
});
NB: for numeric properties use numeric types.
JavaScript objects do not guarantee a specific order for their attributes. So the structure you'd like to have simply doesn't exist in JavaScript.
So with the native structures you can get either:
Array: Guaranteed order, but only accessing elements sequentially or by a numeric (0..n-1) index
Object: Arbitrary order, but you can access elements sequentially (again, arbitrary order) or using its key (which can be any string)
If you need both you either need to add an array that maps the order to the object keys, e.g. [1000, 2010, 1030] or store the data in an array and create a mapping like this: {1000: 0, 2010: 1, 1030: 2}.

Complex JSON string Parsing in JavaScript

This is my sample JSON file , which im trying to parse and read the values ....
C = {{
"Travel": {
"ServiceProvider": {
"Name": "SRS",
"Rating": "3 stars",
"Rates": "Nominal",
"Features": {
"OnlineBooking": "Yes",
"SMS_Ticket": "No"
},
"UserDetails": {
"Name": "Jack",
"Age": "33",
"Gender": "Male"
}
},
"BusProvider": {
"Name": "SRS",
"Rating": "3 stars",
"Rates": "Nominal",
"Features": {
"OnlineBooking": "Yes",
"SMS_Ticket": "No"
},
"UserDetails": {
"Name": "Jack",
"Age": "33",
"Gender": "Male"
}
}
}
}
I'm pretty new to JS , and i need to access the nested elements in a generic fashion.
Im not able to extract the details properly. Im getting stuck accessing nested the child elements.
The problem for me is that i wont always know the names of the "key's' to acess them , the JSON will be dynamic , hence i need a generic mechanism to acess the nested child elements. The Nesting can go upto 3 -4 levels.
what notation do we use to access the key / value pairs when the nesting is deep.
Any Help would be appreciated.
ater desirializing your object you can do this
var resultJSON = '{"name":"ricardo","age":"23"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
//display the key
alert(k + ' is the key)
}
you can do it using recursively offcourse like this - Link Here
the way is the same just adapt to your example
For dynamic access you can use brackets notation i.e. var json = {nonKnown: 1}; now you can access it like that:
var unknowPropertyName = "nonKnown";
var value = json[unknownPropertyName];
But if you can not even define dynamically name of the property, then you should use
for(variableName in json){
if(json.hasOwnProperty(variableName)){
console.log(variableName);
}
}
You should get the basic idea from this. Good luck

Categories

Resources