JSON data to JavaScript - javascript

When I do JArray.toSource(), I get this:-
[{selectionID:"1", cnt:"5"}, {selectionID:"2", cnt:"2"}, {selectionID:"3", cnt:"1"}]
How can I convert JArray to format like this:-
[[1,5],[2,2],[3,1]]
in JavaScript.
Eventually I want newJArray.toSource() become [[1,5],[2,2],[3,1]]

You can use Object.keys which returns the keys, and map to map the array as such:
array.map(function(arrayItem) {
return Object.keys(arrayItem).map(function(objectKey) {
return +arrayItem[objectKey]; // convert to number
});
});
Basically, you replace each element in the array with the values of the object.

pimvdb's solution is very nice. My comment is that in this particular case this is enough:
array.map(function(arrayItem) {
return [arrayItem.selectionID, arrayItem.cnt];
});
It is uglier (more specific), but my gut feeling is that it's much more efficient (and sometimes that matters).

Related

How to convert object into array in angularjs Ionic

Let's say I have an object that looks like this: {first: "asdasd", second: "asdas", third: "dasdas", four: "sdasa"}
I need to convert this object into array.
if(values){
var first=values.first;
var second=values.second;
var third=values.third;
var four=values.four;
var five=values.five;
var six=values.six;
var seven=values.seven;
var eight=values.eight;
var nine=values.nine;
var ten=values.ten;
if(first){
userData.push(first);
}
if(second){
userData.push(second);
}
if(third){
userData.push(third);
}
if(four){
userData.push(four);
}
if(five){
userData.push(five);
}
if(six){
userData.push(six);
}
if(seven){
userData.push(seven);
}
if(eight){
userData.push(eight);
}
if(nine){
userData.push(nine);
}
if(ten){
userData.push(ten);
}
console.log(userData);
I am currently doing by this code but i think it is the wrong approach. So how could i change this to array that looks like ["asdasd", "asdas", "dasdas", "sdasa", "asdasd", "asdas", "dasdas", "sdasa"].
In ionic drag and drop directive doesnot work when i use object in ng-repeat.And works perfectly when i apply array to ng-repeat.
There are several ways you could do it.
One would be using Object.keys:
Object.keys(values).forEach(function(key) {
userData.push(values[key]);
});
You could also use for ... in like this:
for (var key in values) {
userData.push(value[key]);
}
If your object has any properties inherited from prototype then it would also show, so you do need to check if property really belongs to this instance:
for (var key in values) { //proper way to iterate keys using for..in
if(values.hasOwnProperty(key)) {
userData.push(value[key]);
}
}
Since you're using angular, you could also use angular.forEach:
angular.forEach(values, function(value){
userData.push(value);
});
and I think this is the cleanest solution for you.
I would suggest using javascript library underscorejs or lodash for this kind of array and objects manipulation and iteration ,as it seems to be most preferable way of doing it ,keeping your code clean.
Its a simple javascript file that you can include in your project and you don't have to do any complex thing to make it work.Just plug and play.
If you do include underscore/lodash ,all you have to do is :-
var mycoll = _.values(yourobjectvariable);
This will fetch all the values in that object and convert it into an array automatically for you.
http://underscorejs.org/#values
Or if you want to do it with plain javascript , i think the above Randall Flag's answer is suffice for it.
`
if(values)
{
Object.keys(values).forEach(function(key) {
userData.push(values[key]);
});
}
`
Sometimes instead of a simple solution we think too much and end up with complex time taking solution ,which we can achieve with small simple code

How to insert the new array values with previously inserted item at same array index

Lot of questions are available for array push and splice but not like this one.
Please see this fiddle for what i try
JS Fiddle
I have the output like this
[{"rup":"100","dol":"50"},{"rup":"100","dol":"50"},{"expense":
[{"reason":0,"cost":0,"receipt":0,"expense_type":0}]},{"expense":
[{"reason":1,"cost":1,"receipt":1,"expense_type":1}]}]
but what i need is
[{"rup":"100","dol":"50",{"expense":[{"reason":0,"cost":0,"receipt":0,"expense_type":0}},
{"rup":"100","dol":"50",{"expense":[{"reason":1,"cost":1,"receipt":1,"expense_type":1}}]
I tried SPLICE() and ARRAY.INSERT() methods but not get like above.
Please suggest any ideas.
use this piece of code,
for (var i in costArray) {
costArray[i].expense = expenseArray[i];
}
Out put:
[{"rup":"100","dol":"50","expense":{"reason":0,"cost":0,"receipt":0,"expense_type":0}},
{"rup":"100","dol":"50","expense":{"reason":1,"cost":1,"receipt":1,"expense_type":1}}]
SEE THIS FIDDLE DEMO
The format you want in not valid in javascript, I guess you mean this:
{ "rup":"100","dol":"50", "expense":{"reason":0,"cost":0,"receipt":0,"expense_type":0} }
To get this, try replacing
costArray.push({"expense":expenseArray});
with
costArray[i]["expense"] = expenseArray
in the second loop.

Can't get JSON properties to display via jQuery

For some reason I just can't seem to be able to display properties from this JSON string:
http://www.easports.com/iframe/fifa14proclubs/api/platforms/PS4/clubs/51694/members
I've sat here for the last 2-3 hours trying out different ways to select single properties such as the name of the first person in the array. A couple selectors I've tried:
$("#output").append(data.raw[0].176932931.name);
$("#output").append(data.raw[0][0].name);
I always get the same error. "data.raw[0] is undefined". The JSON string is valid, I'm able to output the whole string to my page using:
document.getElementById('output').innerHTML=data.toSource();
Parsing it into a JSON object gives me another error because it already is a JSON object. By using console.log(data) I'm able to view the JSON object properly in Firebug.
data is the name of the Javascript JSON object variable that is being returned from my YQL statement.
Please, if anyone could provide some examples as to how I should go about accessing the properties of the above JSON string, that would be great.
UPDATE:
Here's the callback function from my YQL statement:
function cbfunc(json)
{
if (json.query.count)
{
var data = json.query.results.json;
$("#output").append(data.raw[0]["176932931"].name);
}
You need to use bracket notation, as identifiers starting with digits are invalid
$("#output").append(data.raw[0]["176932931"].name);
as "176932931" is an integer key so you have to access like json["176932931"].
For example
data.raw[0]["176932931"].name
see fiddle here
.count isn't a property of a json object. Try this:
var something = {"raw":[{"176932931":{"name":"Shipdawg","blazeId":176932931,"clubStatus":0,"onlineStatus":0,"nucleusId":2266699357,"personaName":"Shipdawg"},"182141183":{"name":"Beks8","blazeId":182141183,"clubStatus":0,"onlineStatus":0,"nucleusId":2272736228,"personaName":"Beks8"},"219929617":{"name":"ChelseaFC_26","blazeId":219929617,"clubStatus":0,"onlineStatus":0,"nucleusId":2304510098,"personaName":"ChelseaFC_26"},"457588267":{"name":"Lazy__Rich","blazeId":457588267,"clubStatus":0,"onlineStatus":0,"nucleusId":2495578386,"personaName":"Lazy__Rich"},"517570695":{"name":"x0__andrew__0x","blazeId":517570695,"clubStatus":0,"onlineStatus":1,"nucleusId":2549150176,"personaName":"x0__andrew__0x"},"912396727":{"name":"mizz00-","blazeId":912396727,"clubStatus":0,"onlineStatus":1,"nucleusId":1000118566560,"personaName":"mizz00-"},"915144354":{"name":"MisterKanii","blazeId":915144354,"clubStatus":2,"onlineStatus":0,"nucleusId":2281969661,"personaName":"MisterKanii"}}]}
function cbfunc(json)
{
if (json.raw.length)
{
$("#output").append(json.raw["0"]["176932931"].name);
}
}
cbfunc(something);
Tell me if this works for you:
function cbfunc(json)
{
$each(json, function(key, object){
console.log(key, object);
});
var raw = query.results.json.raw;
console.log(raw );
// uncomment it if you want some extra check.
if (/*typeof data.raw !=='undefined' && */data.raw.length > 0)
{
//console.log(data.raw[0]["176932931"].name);
//$("#output").append(data.raw[0]["176932931"].name);
}
}
If this works for you there's no need to reference the object to data, simply use the object its self.
JS fiddle: http://jsfiddle.net/q8xL3/2/

inArray() returns -1 even though element exists in array

$.post('service.php?getPhotos', function(data){
var photoIds = [];
$.each(data, function(){
photoIds.push(this.id);
});
console.log(_photoId); //7962669392
console.log(photoIds); //["7980686507", "7962669392", "7962163506"]
console.log($.inArray(_photoId, photoIds)); //-1
});
Why doesnt console.log($.inArray(_photoId, photoIds)); return 1?
string vs integer I would imagine. Different types would mean that inArray does not see them as the same. Make sure you are using a string instead of an integer and this should work.
It seems like _photoId is a number but photoIds contains strings. Try this:
$.inArray(''+ _photoId, photoIds)
This is because the $.inArray function also takes the type into account. It will not say that an integer is the same as a string. This is also explained in the first comment in the documentation.
You can use _photoId.toString() to get the string representation of the value.
Also note that ECMAScript (Javascript) have a native function called indexOf which does exactly the same thing as the jQuery one:
photoIds.indexOf(_photoId.toString())

getting variable/object elements and values in javascript

I'm not sure if I'm using the correct terminology, so please correct me if I'm not.
I've got a javascript variable which holds a group of values like this
var my_variables = {
first_var: 'starting',
second_var: 2,
third_var: 'continue',
forth_var: 'end'
}
Now I'm trying to get these variables in my script, but I don't want to have to check for each one.
Right now i'm doing this
if(my_variables.first_var!=null){
query=query+'&first_var='+my_variables.first_var;
}
if(my_variables.second_var!=null){
query=query+'&second_var='+my_variables.second_var;
}...
I'm hoping there is a simple way to recursively go through the object, but I haven't been able to find how to do that.
Something like
foreach(my_variables.??? as varName){
query=query+'&'+varName+'='+my_variables.varName;
}
Try this:
for(var key in my_variables)
query += '&'+key+'='+encodeURIComponent(my_variables[key]);
for (var varName in my_variables) {
query=query+'&'+varName+'='+my_variables[varName];
}
for (... in ...) is how you write this kind of loop in Javascript. Also use square brackets instead of a period when the field name is a value instead of the actual identifier, like here. Incidentally, I'd also suggest using window.encodeURIComponent if your values might contain arbitrary text.

Categories