change the value of name: in an object in serialize array - javascript

I am doing this:
var a_survey = $('#survey-1 :input').serializeArray();
$.ajax({
url: "/save_a_survey/",
type: "post",
data: a_survey,
csrfmiddlewaretoken:'{{ csrf_token }}',
});
Which passes this:
csrfmiddlewaretoken:6rS9oNMSJIzJw6ye8nCQZPRkjNemyMOD
form-1-student:12
form-1-behavior_type:Externalizer
form-1-surveyset:13
But I want to change the names of the keys to:
csrfmiddlewaretoken:6rS9oNMSJIzJw6ye8nCQZPRkjNemyMOD
student:12
behavior_type:Externalizer
surveyset:13
This probably seems like quite a hack, but I am dealing with django formsets and trying to save pieces of them at a time; Which may also sound like a hack...
So far I have tried this:
a_survey = $('#survey-1 :input').serializeArray();
for (var i = 1; i <= a_survey.length; i++) {
a_survey[i]['name'] = a_survey[i]['name'].replace(/form-\d-/g, "");
};
But I keep getting...
TypeError: Cannot read property 'name' of undefined
Thanks for the help

You have an off-by-one error in your iteration (JavaScript arrays are zero-based).
var a_survey = $('#survey-1 :input').serializeArray();
for (var i = 0; i < a_survey.length; i++) {
a_survey[i].name = a_survey[i].name.replace(/form-\d-/g, "");
};
Edit: Alternatively, you can use $.each(), per #RobG's suggestion:
var a_survey = $('#survey-1 :input').serializeArray();
$.each(a_survey, function(i, item) {
item.name = item.name.replace(/form-\d-/g, "");
});

Related

Loop through JSON array in Javascript

I have a JSON array which is returned from my PHP ajax call. I need to loop through it and display all the information. I can not seem to get a method working. I am used to using the foreach key => value, in PHP but that doesn't seem to be an option here.
my array is
[{"Type":"Person","Durable":"Durable","Url":"test.com"},
{"Type":"Person","Durable":"Durable","Url":"test2.com"},
{"Type":"Person","Durable":"Durable","Url":"test3.com"},
{"Type":"Person","Durable":"Durable","Url":"test4.com"},
{"Type":"Location","Durable":"Durable","Url":"test5.com"},
{"Type":"Phone","Durable":"Durable","Url":"test6.com"}]
The length of the array changes every time it is not always 6 items.
And the loop is going to go in my success handler. I just need help on how to access the data.
success: function(data){
}
You can use a simple loop statement:
success: function(data){
var i, l;
for (i = 0, l = data.length; i < l; i++) {
// access the object: data[i]
console.log(data[i]);
}
}
This is the most effiecient way.
You can just loop through the array:
success: function(data){
for (var i = 0; i < data.length; i++) {
var obj = data[i];
var type = obj.Type;
var durable = obj.Durable;
var url = obj.Url;
// do work
}
}
You can use the array prototype forEach:
data.forEach(function(item) {
var type = item["Type"];
var durable = item["Durable"];
/*...*/
});

How to parse read json elements with jquery

I have to create cart system in my mobile application, i want to store the id and the quantity of products, the id should be the key of my array (for modifying product quantity) , tried to use object instead of array but i get error: undefined is not a function when i try to read my json variable
by JSON.stringify(cart)
My cart code is like this
var cart = [];
var produit = {};
produit['qte'] = $('.'+id_prd).text();
produit['id_produit'] = id_prd;
cart[id_prd] = produit;
window.sessionStorage["cart1"]= JSON.stringify(cart);
return me
{"7":{"qte":"1","id_produit":7},"8":{"qte":"1","id_produit":8}}
when I tried to parse the json string with
var parsed = $.parseJSON(window.sessionStorage["cart1"]);
i get the error 'undefined is not a function'
when triying to read the json with
var i=0;
for (k in parsed) {
var k_data = parsed[k];
k_data.forEach(function(entry) {
alert(entry);
ch+=entry.id_produit;
if(i<parsed.length-1)
ch+= ',';
if(i==parsed.length-1)
ch+=')';
i++;
});
}
Can you clarify me the error cause, and if there's a solution to better read the json
The problem is that you are using k_data.forEach(function(entry) but forEach is for Arrays, and k_data is just a simple javascript object.
Try changing:
k_data.forEach(function(entry){
to this:
$(k_data).each(function(entry){
Even more, if the JSON is always in the same structure you posted, I think the each function is not necessary, maybe this is the way you are looking for:
var i=0;
var ch = "(";
for (k in parsed) {
var k_data = parsed[k];
alert(k_data);
ch+=k_data.id_produit;
ch+= ',';
i++;
}
ch = ch.substring(0, ch.length - 1) + ")";
You shouldn't need jQuery for this. The same JSON object you used to stringify has a parse function:
var parsed = JSON.parse(window.sessionStorage["cart1"]);
If that still breaks, there's probably something wrong with another undefined object.
You can try something like this:
<script type="text/javascript">
var finalArr = new Array();
var dataArr = new Array();
dataArr = window.sessionStorage["cart1"];
if (JSON.parse(dataArr).length > 0) {
for (var i = 0; i < JSON.parse(dataArr).length; i++) {
finalArr.push((JSON.parse(dataArr))[i]);
}
}
</script>

Array of arrays to object in javascript

I am trying to make an array which then contains mutiple arrays (which are added in the each loop) and then pass the information to ajax to post off.
However, it won't add to the request, and when I try JSON.Stringify on the array, it just returns empty.
What am i doing wrong?
Thanks!
var graphics = new Array();
var customer = "Joe Bloggs";
var email = "joe#bloggs.com";
var contactnumber = "12345";
$('.graphic').each(function (i) {
var graphic = new Array();
graphic['name'] = $(this).attr('data-name');
graphic['type'] = $(this).attr('data-type');
graphic['price'] = $(this).attr('data-price');
graphic['model'] = $(this).attr('data-model');
graphic['carcolor'] = $(this).attr('data-carcolor');
graphic['graphiccolor'] = $(this).attr('data-color');
graphic['reg'] = $(this).attr('data-reg');
graphic['note'] = $(this).attr('data-note');
graphics.push(graphic);
});
$.ajax({
type: "POST",
data: {
customer:customer,
email:email,
contactnumber:contactnumber,
graphics:graphics
},
url: "assets/php/index.php",
success: function(msg){
$('.answer').html(msg);
}
});
graphic inside the .each is an array, however you are treating it as if it were an object. simply change new Array() to {} and it will be more correct, however, still not in an acceptable format. To post that correctly you will need to serialize it as JSON after that.
$('.graphic').each(function (i) {
var graphic = {};
graphic['name'] = $(this).attr('data-name');
graphic['type'] = $(this).attr('data-type');
graphic['price'] = $(this).attr('data-price');
graphic['model'] = $(this).attr('data-model');
graphic['carcolor'] = $(this).attr('data-carcolor');
graphic['graphiccolor'] = $(this).attr('data-color');
graphic['reg'] = $(this).attr('data-reg');
graphic['note'] = $(this).attr('data-note');
graphics.push(graphic);
});
$.ajax({
type: "POST",
data: {customer:customer, email:email, contactnumber:contactnumber, graphics:JSON.stringify(graphics)},
url: "assets/php/index.php",
success: function(msg){
$('.answer').html(msg);
}
});
It looks like you're used to PHP.
When you define an Array:
var graphic = new Array();
You need to treat it as an array:
graphic[0] = "foo";
graphic[1] = "bar";
...and not like an object:
var graphic = {};
graphic['my_property'] = "foobar"
When you do this:
var a = new Array();
a["something"] = 123;
Then a will be an empty array ([]) but a.something will contain 123.
However when you want to stringify a, and a is an Array, it will try to find a stringified representation of that array. And since it is empty, you get [].
So in order to fix your problem, simply change graphic so that it is an object. Note that you end up with an array of objects, not an array of arrays.

Dictionary in JavaScript

Currently I tried to reform my JSON data to a dictionary to store only needed data in an array with key and value.
* Edit to put my full code. *
This is how I do:
var myData = [];
var urlPath = "https://tipjira.pgdev.abcd.com/rest/api/2/search?jql=project=GRIFR14%2Band%2BfixVersion=15018";
var jiraMapping = [];
$.ajax({
url : "http://frparwself22.dhcp.par.abcd.com:8080/jiraproxy/jira?url=" + urlPath,
dataType : 'json',
type: 'GET',
success : function(data) {
for (var i=0; i<data.issues.length; i++) {
var obj = {};
obj[data.issues[i].key] = data.issues[i].self;
jiraMapping.push(obj);
alert(jiraMapping.length);
}
},
error : function() {
alert("Error!")
}
});
alert(jiraMapping.length);
My original data is {issues:[{...,"self":"/rest/api/2/issue/175074","key":"GRIFR14-36",...}, {...,"self":"/rest/api/2/issue/175075","key":"GRIFR14-37",...}, ...]}. And I want to reform to have the array with key and value which are key and self.
So the data in my jiraMapping should be something like [{k1:v1}, {k2,v2}, ...].
But when I tired to print the length of jiraMapping, the length is 0.
I tried to put alert to check key and value that I add to the array and the values exist.
I don't know where is the problem exactly. Please help...
Without knowing exactly what information you're passing in, it's hard to say what's going wrong. That being said, my first guess is that data/myData isn't formatted the way you think. For instance, if myData.issues.length is 0, nothing in the loop will get executed.
There's also a chance that you're never actually running the success function. Could you post some more code?
The problem lies in the data that you are receiving or you have a typo somewhere later when checking length. This all looks fine, and I tried to replicate your problem like this:
var jiraMapping = [];
var myData = [{"A":"a"},{"B":"b"}];
for (var i=0; i<myData.length; i++) {
var obj = {};
obj[myData[i]] = myData[i];
jiraMapping.push(obj);
}
console.log(jiraMapping);
but this works fine, fiddle here: http://jsfiddle.net/GWpBs/2/

Read values from JSON object

I am currently trying to get contents from a JSON object.
I've been looking all over google and what I think should work, for some reason, does not.
The JSON looks something like this:
{"locatie0":{"naam0":["Domplein"],"value0":["value1"]},"locatie1":{"naam1":["Neude"],"value1":["value1"]},"locatie2":{"naam2":["Vredenburg"],"value2":["value1"]},"locatie3":{"naam3":["Stadhuisbrug"],"value3":["value1"]},"locatie4":{"naam4":["Korte Minrebroederstraat"],"value4":["value1"]}}
I use below code to read the file but for some reason it will always return undefined or NaN.
$.ajax({
url: "_data/pleinen.json",
type: 'get',
dataType: "json",
success: function(data) {
for(var k = 0; k < _loc.length; k += 1) {
var _locaties = data.locatie[k].naam[k];
// Should alert "Domplein", "Neude", "Vredenburg", "Stadhuisbrug", "Korte Minrebroekstraat",
alert(_locaties);
}
}
});
Can anybody see if i've made any mistakes in my code or if there's a better way to read the values?
locatie[k] tries to access the property k of the object in locatie, but in your case, the number is part of the name itself. You have to build the property name dynamically. In addition, each property of the nested objects is an array with one element, so you have to access the first element:
var _locaties = data['locatie' + k]['naam' + k][0];
Your data structure is a bit strange though. The numbers in the property names makes accessing the data more difficult. If you can change it, change it to an array of objects and don't use arrays for the properties if you don't need them:
[{"naam": "Domplein", "value": "value1"}, {"naam": "Neude", "value":"value1"}]
Then accessing the data is simply:
for (var i = 0, l = data.length; i < l; i++) {
var _locaties = data[i].naam;
}
A JSON does not guarantee any order like an array.
But in your case, the keys of the JSON have index hints, so try accessing "naam" with:
data["locatie" + k]["naam" + k]
Try this:
$.ajax({
url: "_data/pleinen.json",
type: 'get',
dataType: "json",
success: function(data) {
for(var k = 0; k < _loc.length; k += 1) {
var _locaties = data['locatie'+k]['naam'+k][0];
alert(_locaties);
}
}
});
As the value of naam property is array you need to fetch first item from it in order to get string value.
The locatie and the naam are not arrays, so you cannot access them like the way you do.
You have to combine the number with the name as a string. Something like that
data['locatie'+k]
try this ;
k = 0;
console.log(
data[ 'locatie'+ k]['naam'+ k][0],
data[ 'locatie'+ k]['value'+ k ][0]
);
k = 1;
console.log(
data[ 'locatie'+ k]['naam'+ k][0],
data[ 'locatie'+ k]['value'+ k ][0]
);

Categories