I have an empty json object like this
var image, description ;
var json = { 0 : { image : " " , description : " " } };
I want to populate like this by looping through n but this way of adding properties it gives be this error : "cannot set property description of undefined"
json[n].description = " nth description";
json[n].image = " nth image";
In the end I want var json to be like this
var json = { 0 : {"image" : "1st image", "description" : "2nd description" }
1 : {"image" : "2nd image", "description" : "2nd description" }
2 : {"image" : "3rd image ", "description" : "3rd description" }
3 : {"image" : "4th image ", "description" : "4th description" }
}
and so on .... I get the undefined error on the first iteration so I haven't even attempted adding the second or third elements yet so not sure if that would need something else.
I have an empty json object like this
var image, description ;
var json = { 0 : { image : " " , description : " " } };
I want to populate like this by looping through n but this way of adding properties it gives be this error : "cannot set property description of undefined"
json[n].description = " nth description";
json[n].image = " nth image";
In the end I want var json to be like this
var json = { 0 : {"image" : "1st image", "description" : "2nd description" }
1 : {"image" : "2nd image", "description" : "2nd description" }
2 : {"image" : "3rd image ", "description" : "3rd description" }
3 : {"image" : "4th image ", "description" : "4th description" }
}
and so on .... I get the undefined error on the first iteration so I haven't even attempted adding the second or third elements yet so not sure if that would need something else.
Share Improve this question asked Jul 16, 2015 at 9:45 jojojohnjojojohn 7532 gold badges10 silver badges19 bronze badges 1- In the console it is working fine for me... May be you are iterating even when other element hasn't been created ... Instead you should make a child object and push it to an array instead of this json type object. Something like this : var json = [ {image : , description : }] – binariedMe Commented Jul 16, 2015 at 9:49
3 Answers
Reset to default 4Because in your example, if n
is anything else than 0
, the object is undefined.
Create the empty object before using it :
json[n] = {};
json[n].description = " nth description";
json[n].image = " nth image";
You can do it like this :
var json = {}
json[n] = {}
json[n].description = " ....."
json[n].image = " ..... "
You need to create the new object inside the original and then declare its properties.
you can code like this.
var nt = ['st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th'];
var json = {};
for(var i=0;i<n;i++) {
var tp = json[i] = {}; //define first if it a object otherwise it say undefined.
tp['image'] = i+nt[(i%10)]+' image';
tp['image'] = i+nt[(i%10)]+' description';
}
console.log(json);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745558399a4632958.html
评论列表(0条)