Array of arrays to object in javascript - 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.

Related

filter json from array values with underscore

I have an array of object that is need to create a filter on. The list contains an owner_id property in the JSON...
At the moment im just looping all in the array, however the list should NOT take the ones where owner_id is equal to one of the values in my filterarray:
var filter = "[14657612, 2215375794]";
$.ajax({
url: 'myEndPOint',
dataType: 'json',
success: function(data) {
var media = data.media;
var arr = [];
_.filter(media, function(val){
//The magic should happen here, only return items that has'nt got an val.owner_id that is in "filter" array
});
for(i=0; i < media.length; i++) {
var thumb = media[i].thumbnail;
var html = "<li><img src=" + thumb + " /></li>";
arr.push(html);
}
$(".social-ribbon-target").append(arr);
$(".loading").css("display", "none");*/
},
error: function(error) {
console.log("error");
}
});
You defined filter has a string, instead of an array.
Change:
var filter = "[14657612, 2215375794]";
To:
var filter = [14657612, 2215375794];
The magic should happen here
It is actually not magic, but a function that returns true or false whether the item should be in the returned array.
Assuming that your filter is an array and not a string as it is right now (otherwise you have to parse it with filter_arr = JSON.parse(filter)) you may want to write your filtering function like this:
var filter = ["one", "two", "three"];
var media = [{owner_id: "one"}];
console.log(_.filter(media, function(item){
return filter.indexOf(item.owner_id) >= 0;
}))
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Javascript multidimensional array not working

How to create multidimensional array??
I tried it so far:
var post_data = [];
var id = 1;
post_data[id] = [];
post_data[id]['name'] = 'abc';
post_data[id]['date'] = '01-03-2014';
post_data[id]['country'] = 'India';
console.log(post_data);
the above code is not giving me the key. Whats wrong?
DEMO FIDDLE
i want a output something like this:
[1]=> array
(
"name": "abc",
"date": "01-03-2014",
"country": "India",
)
How to get the above output???
To get wished result you can change
var post_data = [];
to
var post_data = {};
and
post_data[id] = {};
You are trying to make an array of object.
Try this : -
post_data[id] = {};
You are using the inner array as an object. The properties that you set on the array still is there, when you display it only the array items are shown.
You should use an object instead of an array, as you are not using the array as an array:
post_data[id] = {};
Instead of setting the properties after creating the object, you can set them when you create it:
post_data[id] = {
name: 'abc',
date: '01-03-2014',
country: 'India'
};
In the third line of code you have to write
post_data[id] = new Array();
So the entire code section looks like
var post_data = [];
var id = 1;
post_data[id] = new Array();
post_data[id]['name'] = 'abc';
post_data[id]['date'] = '01-03-2014';
post_data[id]['country'] = 'India';
console.log(post_data[id]['name']);
This should fix it, best of luck :)

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

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, "");
});

Setting dynamically an Object in JavaScript

It seems complicated for me.
First, I have this list:
liste_path_categories.push(
{ index: null
, letter: "letter1"
, type: key
, picture_url: "url1"
, id_categ: null
, response: "Answer here"
});
What I want is to extract from this big list an object in this form:
data["String1"]["String2"]= String3
With :
String1=list_path_categories[i].letter
String2=list_path_categories[i].id_categ
String3=list_path_categories[i].response
example:
data['A']['12'] : "A_answer"
To declare the data i make this:
var data = new Object(new Object);
How I can set all the values in data?
You can use the Array.forEach method to iterate through liste_path_categories and construct your data object.
Example:
var liste_path_categories = [];
var data = {};
liste_path_categories.push(...);
...
liste_path_categories.push(...);
liste_path_categories.forEach(function(element) {
data[element.letter] = {};
data[element.letter][element.id_categ] = element.response;
});
jsFiddle example : http://jsfiddle.net/3ZvNf/
Your question is pretty vague but do you mean something like this?
Setting a dynamic property in an object wich belongs to another object?
data['A']['12'].answer = "A_answer"
Instead of using strings, you have to use the variables in your property access:
var data = {};
if (!data[String1]) {
data[String1] = {}; // make sure that data[String1] exists and is an object
}
data[String1][String2] = String3;
If you want to do this for elements in the array, you have to iterate over the array.
P.S.: I recommend to use more expressive variable names than StringX.
first create the constructor (in OOP terminology):
var ctor_object = function(letter,id_categ,response)
{
this.letter = letter;
this.id_cated = id_categ;
this.response = response;
}
(in genereal you should omit the ctor_ syntax and name it directly after the name of the class of your object)
then use your constructor upon your list of categories:
var length = liste_path_categories.length,
element = null;
for (var i = 0; i < length; i++)
{
element = liste_path_categories[i];
my_obj = new ctor_object(element.letter,element.id_categ,element.reponse)
// Do something with my_obj
}

How do I retrieve the first value from an array?

I have a call to a YouTube XML sheet that works perfectly fine. However, I am having trouble setting a value from one of the arrays. I want the first value from "songID" to be set as "first". I've tried doing this:
var first = songID[0]
but it only makes a new array with only the first character of each value... Any suggestions?
$(window).load(function(){
var pURL = 'http://gdata.youtube.com/feeds/api/playlists/F9183F81E7808428?v=2&alt=json&callback=?';
$.getJSON(pURL, function(data) {
$.each(data.feed.entry, function(i, item) {
var songID = item.media$group.media$content[0].url.substring(25, [36]);
var songTitle = item.title.$t;
var descript = item.media$group.media$description.$t;
var songAth = descript.slice(3);
}
}
})
You are already in an each() loop, so you shouldn't try to access it as an array, but just as a value. Just try:
if(i == 0){
var first = songID;
}
Are you sure what you're getting is actually an array? What makes you think that? Because if you ask for aString[0], you'll still get the first character back, because you can access string characters as if they're array elements. If it is indeed an array, just use var myString = myArray.join(""); and it'll become a string.
$(document).ready(function() {
var pURL = 'http://gdata.youtube.com/feeds/api/playlists/9002A5F66694EBA0?v=2&alt=json&callback=?';
$.getJSON(pURL, function(data) {
$.each(data.feed.entry, function(i, item) {
var songID = item.media$group.media$content[0].url.substring(25, [36]);
var songTitle = item.title.$t;
var descript = item.media$group.media$description.$t;
var songAth = descript.slice(3);
if(i==0){
alert("firstId is "+songID );
}
});
});
});
or just for first id:
var pURL = 'http://gdata.youtube.com/feeds/api/playlists/9002A5F66694EBA0?v=2&alt=json&callback=?';
$.getJSON(pURL, function(data) {
console.log(data.feed.entry[0].media$group.media$content[0].url.substring(25, [36]));
});
});

Categories