push object to array and eventually convert array to json - javascript

I am creating an object and pushing it into array.Then I convert it into json.When I alert dataCharts it is returned as:
[{"AllLinks":"Link9","LinkURL":"url1"},{"AllLinks":"Link6","LinkURL":"url2"}]
Whereas I want it as:
[{AllLinks:"Link9",LinkURL:"url1"},{AllLinks:"Link6",LinkURL:"url2"}]
My code is as follows:
$.ajax({
url: url,
type: "get",
headers: {"Accept": "application/json;odata=verbose"},
success: function (data) {
var array = new Array();
var temp = new Object();
for (var i=0; i< data.d.results.length; i++) {
var it=data.d.results[i];
array.push({
"AllLinks": it.AllLinks,
"LinkURL": it.LinkURL.Url
});
}
dataCharts=JSON.stringify(array);
alert(dataCharts);
AddDefaultLinks(dataCharts);
},
error: function (data) {
alert(data.responseJSON.error);
}
});

Hint:
[{"_aaaa_":"bbbb","_cccc_":"eeee"}]
[{aaaa:"bbbb",cccc:"eeee"}]
If you want to remove the quotes: name your label like this:
_AllLinks_: it.AllLinks,
_LinkURL_: it.LinkURL.Url
and then remove the underscores and the quotes like this:
dataCharts.replace(/"_|_"/g,"")
But be carefull that this does not conflict with other data (or take two _ or so)

Related

How do i create a table from a json file with multiple objects?

I used this:
$.ajax({
dataType: "json",
url: "Bibliothek.json",
data: data,
success: function(response) {
console.log(response, "response");
},
});
to give me a response of my json file which looks this:
https://pastebin.com/2LU5DwRr
What i get back is:
I want to create a table of each object but i fail in doing so because i never worked with objects before.
$.ajax({
dataType: "json",
url: "Bibliothek.json",
data: data,
success: function(response) {
console.log(response, "response");
let lib = response;
var allarrays = lib.length;
if (allarrays > 0) {
var table = document.createElement("table");
table.style.width = '50%';
table.setAttribute('border', '1');
table.setAttribute('cellspacing', '0');
table.setAttribute('cellpadding', '5');
var col = [];
for (var i = 0; i < allarrays; i++) {
for (var key in lib[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
};
}
},
});
I understand that my code is not working because the lenght of lib is 1 because it doesnt look into each object.
I just dont know how to access all the objects.
If you have nested objects like the one in the pastebin, you can use the inbuilt object methods like Object.keys(), Object.values() and Object.entries() to loop through the response object you are handling.

check if a value exist in javascript array of object fetched from ajax response and delete it

In the following code i am not able to filter entry.AllLinks.
The code is as follows:
$.ajax({
url: url,
type: "get",
headers: {"Accept": "application/json;odata=verbose"},
success: function (data) {
var c = [];
var stringData = JSON.stringify(data.d.results[0].AllLinks);
//alert(stringData);
c.push(JSON.parse(stringData));
alert(c);
var xonly = c.filter(function (entry){
return entry.AllLinks != x;
});
alert(xonly);
},
error: function() {
alert('fail');
}
});
}
It does not filter and when i hover cursor over AllLinks in entry.AllLinks it is undefined.
Value of entry is coming as:
[{"AllLinks":"Link9","LinkURL":"http://www.Link9.com"},{"AllLinks":"Link6","LinkURL":"http://www.Link6.com"}]
You can use Array.filter to filter the array as per the values you require.
let arr = [{"AllLinks":"Link9","LinkURL":"http://www.Link9.com"},{"AllLinks":"Link6","LinkURL":"http://www.Link6.com"}] ;
arr = arr.filter(function(elem) {
return elem.AllLinks !== 'Link9';
});
console.log(arr);

Convert from JSON to array of objects

I'm trying to convert an array of Hazards(class that i created) to JSON,
this is my code:
$.ajax({
async: true,
url: web + "/GetHazards",
method: "POST",
contentType: "application/json",
success: function (data) {
var res = data.d;
var i;
alert(res[0]);
the returned data is like this :
"[{\"Hazard_ID\":3014,\"Hazard_Lat\":32.2615929,\"Hazard_Long\":35.01423},{\"Hazard_ID\":3013,\"Hazard_Lat\":32.3426857,\"Hazard_Long\":34.9103165},{\"Hazard_ID\":3012,\"Hazard_Lat\":32.3426857
My server side code returns the correct values that i need, but the problem is when i alert the res[i] it behave like res is a string and alerts me "["
what i need to get is
{\"Hazard_ID":3014,\"Hazard_Lat\":32.2615929,\"Hazard_Long\":35.01423}
i dont know if it mind this is my server-side code by the way:
{
List<Returned_Hazard> rh = new List<Returned_Hazard>();
JavaScriptSerializer json = new JavaScriptSerializer();
.
.
.
while (reader.Read())
{
Returned_Hazard RH = new Returned_Hazard(
int.Parse(reader[0].ToString()),
float.Parse(reader[1].ToString()),
float.Parse(reader[2].ToString())
);
rh.Add(RH);
}
command.Connection.Close();
return json.Serialize(rh);
}
You need to parse the JSON, using JSON.parse:
var data = { d: "[{\"Hazard_ID\":3014,\"Hazard_Lat\":32.2615929,\"Hazard_Long\":35.01423},{\"Hazard_ID\":3013,\"Hazard_Lat\":32.3426857,\"Hazard_Long\":34.9103165}]"
};
var res = JSON.parse(data.d);
console.log(res[0].Hazard_ID); //3014

Make array jquery/js

I want to make an array like this. (on alert it gives object)
var playlist = [{"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"}];
From:
var playlist = [];
$.ajax({
url: 'url.php',
data: {
album_name: album_name
},
type: 'POST',
success: function( data ) {
var data_array = JSON.parse(data);
for( var i=0; i<data_array.length; i++ ) {
var value = data_array[i].split('::');
playlist.push('{"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"},'); // putting the same thing just for testing.
}
alert(playlist);
}
});
Now the new array playlist didn't seem to be working for me. i guess there is something wrong the way i am creating an array like above.
you need to push object instead of object string:
playlist.push({"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"});
//------------^---remove the single quote.
Try this one
var playlist =[{"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"}];
alert(JSON.stringify(playlist));
Use jQuery.map() for making array.
playlist = $.map(data_array, function(val, i){
splitArr = val.split('::')
return {
'title':splitArr[0],
'mp3':splitArr[1]
}
})
As #Jai said you need to push an object: playlist.push({"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"});
Arrays in JavaScript are objects.
You'd be better using the console to log or debug your javascript.
In this fiddle you can see
that the array is created and the object pushed to it but its
still logged as an object.
And since you are using jQuery it has a method isArray() to determine if
something is an array or not.
or you can try like this
var playlist = [];
$.ajax({
url: 'url.php',
data: {
album_name: album_name
},
type: 'POST',
success: function( data ) {
var data_array = JSON.parse(data);
for( var i=0; i<data_array.length; i++ ) {
var value = data_array[i].split('::');
var ArrObj = '{"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"},';
playlist.push(ArrObj);
}
alert(playlist);
}
});

jqGrid Initialize DropDownList Items

I have a jqGrid control which includes a dropdownlist field. The items in the list come from a method on the server side using ajax, but I'm not sure how to structure the returned json to make it compatible with the grid. I looked at this question and according to the answers, it seems like the grid expects the following format for dropdowns:
[value] : [display text]
I'm relatively new to JavaScript and am not sure what type of data this is (I'm assuming it's a key-value pair?) so I don't know how create an array of this type from my json object. This is what I tried:
function populateTable(){
$.ajax({
type: "POST",
url: "MyHttpHandler.ashx",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var jsonObject = jQuery.parseJSON(result.d);
var dropdpwnvalues = new[];
for(var i = 0; i< jsonObject.length; i++){
dropdpwnvalues.push({ jsonObject[i].id : jsonObject[i].name });
}
// The rest of the function
);
}
dropdpwnvalues variable is the one that gets bound to the grid. Note that jsonObject does have an id and name on it, but this syntax
dropdpwnvalues.push({ jsonObject[i].id : jsonObject[i].name });
is obviously incorrect. Any ideas how I can make the list from this json object?
I figured the easiest way to do this is by creating a string instead of an object array:
var sessionStream = ""
for (var i = 0; i < sessions.length; i++) {
sessionStream += sessions[i].id + ":" + sessions[i].name + ";";
}
// Remove the trailing ';' in the stream
sessionStream = sessionStream.substring(0, sessionStream.length - 1);
I originally thought the grid was expecing a list. It can bind to a string just fine.
You need to return JSON value of the Select list in following format :
{1:'One',2:'Two'}
And , i believe you are using this in loadcomplete event of jqGrid. So, to set the JSON value simply use it as ,
loadcomplete : function(){
$.ajax({
type: "POST",
url: "MyHttpHandler.ashx",
dataType: "json",
success : function ( result) {
$("#gridId").setColProp('columnName', { editoptions: { value: result}});
}
});
}

Categories