Traversing a JSON object - javascript

The data which I fetch from PHP page is like:
[{
"id": "1",
"name": null,
"startdate": "2012-07-20",
"starttime": "09:53:02",
"enddate": "2012-07-20",
"endtime": "09:54:10",
"duration": "01:00:00",
"feedbacks": [{
"id": "1",
"type": "1",
"content": "cont"
}],
"conditions": [{
"id": "1",
"dev_id": "1",
"mod_id": "2",
"sub_id": "3",
"to_be_compared_value": "1",
"comparison_type": "1"
}],
"actions": [{
"id": "1",
"dev_id": "1",
"mod_id": "1",
"sub_id": "1",
"target_action": "1"
}]
}]
Which way is easy, efficent and elegant to traverse this object? I used this two until this time. Can you tell me which one must be my choice, or can you give me an alternative? And why? I have a running version of my application and I'm reviewing now my own code, and I want to take some advices from you all.
Thanks in advance,
Methods I use before:
$.map
for(var i in obj)
One more to go, I will create a table from this data.

I would use jQuery's each() (or map() if I wanted to change the data)
I should add that you should also create a function which returns an object (possibly even with some utility methods), since your data isn't very JS-friendly right now. Those dates and times, those ID's as strings.
Example:
function cleanMyObject(object){
var cleanFeedbacks = function(feedbacks){
/* ... */
return feedback;
};
object.start = /* transform date and time strings to datetime object ...*/
object.end = /*...*/
/*...*/
$.map(object.feedbacks,cleanFeedbacks);
/* cleanup the remaining objects... */
return object;
}
$.map(receivedData, cleanMyObject);
// cleanMyObject() returns the modified object so $.map will clean everything in your array.

I prefer to use http://underscorejs.org/ for things like this. It has a lot of useful functions for objects, collections etc.

If the data you are recieving doesn't change, just parse the object and use the keys you need.
All browsers I'm aware of have a function called JSON.parse to convert a JSON string into a JS object.
What I'm trying to say is: Don't be lazy, you aren't gaining any benefits from writing a "general" function if your object will always provide the same data, and there is little to no chance you can use that function again with a different object.
var myobj= JSON.parse(phpJSONstring);
var feedbacks= myobj["feedbacks"];
//do something with feedbacks
var conditions= myobj["conditions"];
//do something with conditions
etc

You can transform the json string in a javascript object, and then access the object like this:
var obj = jQuery.parseJSON(jsonString);
alert('Id='+obj.id);
var feedbackList = obj.feedbacks;
for (var i=0; i<feedbackList.length; i++) {
...
}
Reference to jQuery.parseJSON: http://api.jquery.com/jQuery.parseJSON/

Related

Retrieve object with a key in javascript

I have following object, and if I want to retrieve only soccer, then I put soccer as follows,
sports['soccer'] does not bring it.
I wonder what I am missing here?
sports = [] ;
sports = [{
"soccer": {
"type": "foot",
"player": 11
},
"basketball": {
"type": "hand",
"player": 5
}
}]
Your current code creates an array with a single object. One solution is to just create an object instead:
sports = {
"soccer": {
"type": "foot",
"player": 11
},
"basketball": {
"type": "hand",
"player": 5
}
}
Now you can use sports.soccer or sports['soccer'] to access the soccer data.
If you really want an array of objects, you first need to subscript the array to get the first object:
sports[0].soccer
or
sports[0]['soccer']
var sports is an array with objects inside.
If you set it up like this:
sports = [] ;
sports = {
"soccer": {
"type": "foot",
"player": 11
},
"basketball": {
"type": "hand",
"player": 5
}
}
then you will be able to call sports['soccer'] or even sports.soccer.
Alternately, if you need it to remain an array, then you'll need to do more work.
Something like this should do the trick.
for(i=0; i < sports.length; i++) {
if("soccer" in sports[i]){
console.log(sports[i].soccer.type);
console.log(sports[i].soccer.player);
}
}
The console.logs represent whatever you want to do with the values
I think you really need to reiterate the basics of javascript a bit.
In JS we can create data structures on the fly with literal syntax. For example:
let normalArr = new Array();
let literalArr = [];
let normalObj = new Object();
let literalObj = {};
When you create arrays and objects with literal syntax you can initialize arrays with elements and object with properties on the fly. This is what exactly happened in your example:
sports = [{
"soccer": {
"type": "foot",
"player": 11
},
"basketball": {
"type": "hand",
"player": 5
}
}];
The code can be broken down in the following way:
You created an array which was stored in the sports variable using the array literal syntax (created an array on the fly).
You created 1 element of the array with the object literal syntax (creating an object on the fly)
This object (located inside the array) has 2 properties, soccer and basketball which are also object created with object literal syntax.
To access one of there objects you need to do the following:
const sports = [{
"soccer": {
"type": "foot",
"player": 11
},
"basketball": {
"type": "hand",
"player": 5
}
}];
// accessing the first element of the sports array
console.log(sports[0].soccer);
console.log(sports[0].basketball);
As others have pointed out, you have an array of objects, not a single object. You can use the find() method to find the element that has the soccer property, and then access that property.
var soccer = sports.find(s => 'soccer' in s)['soccer'];

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.

How do I create a subset of a JSON file using key values that exist in both using getJSON?

I have a large JSON file that I want to use to create a subset using vars that I'll be storing in localStorage. I prefer jQuery but other approaches are welcomed.
The id (which will exist in both places) will be used to match and determine that the keys/values should be part of the new subset.
The "master" JSON file is structured similar to this:
{
"myStuff": [
{
"id": "53b0c01de4b0deedb5c9015f",
"brief": "Joe's Stuff",
"author": "Joe"
},
{
"id": "545fb8c4e4b03cfb303de9f2",
"brief": "Jim's Stuff",
"author": "Jim"
},
{
"id": "54676ae4e4b09ffed41ffc7c",
"brief": "Mary's Stuff",
"author": "Mary"
}
]
}
I have flexibility in how the items that will determine the subset are presented.It will always contain multiple values. Those are "id" value to match an existing "id" value in the master JSON file.
For example, I can get a string out of localStorage that would look like this:
{"id1":"545fb8c4e4b03cfb303de9f2","id2":"54676ae4e4b09ffed41ffc7c"}
or as simple as this:
545fb8c4e4b03cfb303de9f2, 54676ae4e4b09ffed41ffc7c
Suggestions to which approach may be better are welcomed.
So, in this case, The subset should return just the stuff from Jim and Mary and ignore Joe.
{
"myStuffSubset": [
{
"id": "545fb8c4e4b03cfb303de9f2",
"brief": "Jim's Stuff",
"author": "Jim"
},
{
"id": "54676ae4e4b09ffed41ffc7c",
"brief": "Mary's Stuff",
"author": "Mary"
}
]
}
Please let me know if I've missed something in the explanation. And, I find fiddles help me learn the best. Thanks!
I've created a plnkr for you.
Basically, the filter function will get the string separated by commas and search inside your JSON:
function search(str, obj) {
var arr = str.split(',');
return obj.myStuff.filter(function(o) {
return arr.indexOf(o.id) > -1;
});
}

Add data to end of ko.observablearray

I'm trying to add data to the end of an observable array but it's just not working as expected. I bet it is something minor but I just can't get my head around it.
What I am doing:
self.businesses = ko.observableArray();
function Business(business) {
var self = this;
self.BusinessID = ko.observable(business.BusinessID );
self.Type = ko.observable(business.Type);
self.Location = ko.observable(business.Location);
}
/*ajax get array of businesses as follows:
[
{
"$id": "1",
"BusinessID ": 62,
"Type": "Data",
"Location": "Data"
},
{
"$id": "2",
"BusinessID ": 63,
"Type": "Data",
"Location": "Data"
},
{
"$id": "3",
"BusinessID ": 64,
"Type": "Data",
"Location": "Data",
} ]
*/
var mappedBusinesses = $.map(data, function (business) { return new Business(business) });
self.businesses(mappedBusinesses);
This all works as expected and the obersablearray is populated.
However if I go to add another business, it wont work. For example, if I call the ajax that returns this (as newBusiness):
{
"$id": "1",
"BusinessID ": 68,
"Type": "Data",
"Location": "Data"
}
and I do:
self.businesses().push(newBusiness);
It adds to the array as an "Object" not a Business. So I thought I would do:
var bus = $.map(newBusiness, function (business) { return new Business(business) });
self.businesses().push(bus);
But I get the error in the JS console "Uncaught TypeError: Cannot read property 'BusinessID' of null
So I made a new var and added the brackets: [] in and it adds to the observable array but not as a "Business" object but rather as an "Array[1]" object at the end and this doesn't function as per the others. Code as follows:
var newBus = {
BusinessID: newBusiness.BusinessID,
Type: newBusiness.Type,
Location: newBusiness.Location
}
var bus = $.map(newBus, function (business) { return new Business(business) });
self.businesses().push(bus);
As mentioned this adds to the observable array but doesn't actually add as a "business" object but rather as an "array[1]" object.
I bet it's something so basic but just can't get it working!
Argh I knew it would be simple!
It was posting the whole array to the ObservableArray...not just the object.
The fix:
self.businesses.push(newBusiness[0])
Had to add the [0] in to get it to push the actual data into the array, not the object!
Thanks for the answers!
You're evaluating the array with your push:
self.businesses().push(newBusiness);
Observable Arrays have their own array functions, you should just do this (no parens):
self.businesses.push(newBusiness);
See this page: http://knockoutjs.com/documentation/observableArrays.html

Simplify an associative array

I'm hitting an api built using CakePHP. Cake returns its objects like this:
[
{
"Note": {
"id": "1",
"clas": "test",
"obj_id": null,
"note": "test"
}
},
{
"Note": {
"id": "2",
"clas": "another",
"obj_id": null,
"note": "another"
}
}
]
What I want to do is take that result and basically get rid of the keys. Something like this:
[
{
"id": "1",
"clas": "test",
"obj_id": null,
"note": "test"
},
{
"id": "2",
"clas": "another",
"obj_id": null,
"note": "another"
}
]
I'm basically just trying to make it easier to reference this in Angular. I need to do this on the client side. Any ideas?
You could refactor it like so:
var json = '[{"Note":{"id":"1","clas":"test","obj_id":null,"note":"test"}},{"Note":{"id":"2","clas":"another","obj_id":null,"note":"another"}}]';
var obj = JSON.parse(json);
var arr = [];
for (i = 0; i < obj.length; i++)
{
arr.push(obj[i].Note);
}
Working example here
(Note also that if your key value 'Note' isn't always the same, this will change dramatically. It's likely that 'Note' isn't going to be the same in each instance either; that would generate an improperly keyed object. Alternatively, if you always need the first object in the array, you could use obj[i][0] instead).
(More note if you're using cakephp, this would be much easier done using Hash::, but if you need to do it client side, this is the solution).

Categories

Resources