Simplify an associative array - javascript

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

Related

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.

Converting JSON/JS Object to array

I have a JSON response from my API that is structured like so:
{
"data": [
{
"id": "1", "name": "test"
},
{
"id": "2", "name": "test2"
}
]
}
When I reference data I get the array with each record. I need the curly braces to be brackets due to a plugin I am using requiring it to be an array.
Desired output:
[
["1", "test"],
["2", "test"]
]
How can I convert the above JSON to this?
Edit:
This turned out to be a problem with a plugin I was using, and I knew how to do this fine all along. Thought I was going crazy but my code was fine, some plugin was screwing things up.
You can do this using Array.prototype.map
var arr = json.data.map(function(x){
return [x.id, x.name];
});
Something like this maybe: http://jsfiddle.net/3gcg6Lbz/1/
var arr = new Array();
var obj = {
"data": [
{
"id": "1", "name": "test"
},
{
"id": "2", "name": "test2"
}
]
}
for(var i in obj.data) {
var thisArr = new Array();
thisArr.push(obj.data[i].id);
thisArr.push(obj.data[i].name);
arr.push(thisArr);
}
console.log(arr);

How to filter a JSON tree according to an attribute inside

I have to re-post this questions with more details again:
I got a JSON tree array.
The structure of JSON tree looks like this:
{
"app": {
"categories": {
"cat_222": {
"id": "555",
"deals": [{
"id": "73",
"retailer": "JeansWest"
}, {
"id": "8630",
"retailer": "Adidas"
}, {
"id": "11912",
"retailer": "Adidas"
}]
},
"cat_342": {
"id": "232",
"deals": [{
"id": "5698",
"retailer": "KFC"
}, {
"id": "5701",
"retailer": "KFC"
}, {
"id": "5699",
"retailer": "MC"
}]
}
}
}
}
now, I'd like to filter this JSON tree with var pattern="KF",
return all with retailer name contains KF with it's id.
======================update===========================
Just check my other question. It got solved.
filter multi-dimension JSON arrays
Use Array.filter or _.filter if you need to support IE < 9
Well, you can use _.filter:
var filteredArray = _.filter(arrayOfStrings, function(str) {
return str.indexOf(data) !== -1; });
... or jQuery.grep:
var filteredArray = $.grep(arrayOfStrings, function(str) {
return str.indexOf(data) !== -1; });
As you see, the approaches are quite similar - and, in fact, both use Array.filter, if it's available in the host environment.
Also note that the original array is not affected here. If you want otherwise, just assign the result of filtering to the same variable (i.e., arrayOfStrings in this example).

How to change the order of a JavaScript object?

My JavaScript object looks like this:
"ivrItems": {
"50b5e7bec90a6f4e19000001": {
"name": "sdf",
"key": "555",
"onSelect": "fsdfsdfsdf"
},
"50b5e7c3c90a6f4e19000002": {
"name": "dfgdf",
"key": "666",
"onSelect": "fdgdfgdf",
"parentId": null
},
"50b5e7c8c90a6f4e19000003": {
"name": "dfdf",
"key": "55",
"onSelect": "dfdffffffffff",
"parentId": null
}
}
Now I want to change the order of the object dynamically.
After sorting, the object should look as follows:
"ivrItems": {
"50b5e7bec90a6f4e19000001": {
"name": "sdf",
"key": "555",
"onSelect": "fsdfsdfsdf"
},
"50b5e7c8c90a6f4e19000003": {
"name": "dfdf",
"key": "55",
"onSelect": "dfdffffffffff",
"parentId": null
}
"50b5e7c3c90a6f4e19000002": {
"name": "dfgdf",
"key": "666",
"onSelect": "fdgdfgdf",
"parentId": null
}
}
Is there any possible way to do this?
To get and then change the order of an Object's enumeration, you need to manually define the order. This is normally done by adding the properties of the object to an Array.
var keys = Object.keys(data.ivrItems);
Now you can iterate the keys Array, and use the keys to access members of your irvItems object.
keys.forEach(function(key) {
console.log(data.irvItems[key]);
});
Now the order will always be that of the order given by Object.keys, but there's no guarantee that the order will be what you want.
You can take that Array and reorder it using whatever ordering you need.
keys.sort(function(a, b) {
return +data.irvItems[a].key - +data.irvItems[b].key;
});
This sort will sort the keys by the nested key property of each object after numeric conversion.
You should use an Array. Object keys has no order
like this:
{
"ivrItems": [
{
"id": "50b5e7bec90a6f4e19000001",
"name": "sdf",
"key": "555",
"onSelect": "fsdfsdfsdf"
},
{
"id": "50b5e7c8c90a6f4e19000003",
"name": "dfdf",
"key": "55",
"onSelect": "dfdffffffffff",
"parentId": null
},
{
"id": "50b5e7c3c90a6f4e19000002",
"name": "dfgdf",
"key": "666",
"onSelect": "fdgdfgdf",
"parentId": null
}
]
}
You're probably going to have a tough time with cross-browser compatibility, if you're doing this in the browser. But computers are mostly deterministic, so you could probably accomplish this reliably in one javascript engine implementation, though. For example, in the Chrome REPL / console, you can get this order simply by sequencing adding the properties:
var n = {}
n.b = 2
n.c = 3
var m = {}
m.c = 3
m.b = 2
JSON.stringify(n)
> "{"b":2,"c":3}"
JSON.stringify(m)
> "{"c":3,"b":2}"
So you could reconstruct your object, adding the keys in the order you want to find them later.
But the other people are right, if you want true, predictable order, you should use an array.
Javascript objects are intrinsically unordered.
You can't do that.

Traversing a JSON object

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/

Categories

Resources