i want to push value multidimensional array. But I could not success.
var e = [];
var data = [];
var element = {}, items = [];
e = getelement("alan");
for(s=0;s < e.length ; s++ ){
element.resim = $( "#"+e[s] ).val();
element.baslik = $( "#"+e[s] ).val();
element.icerik = $( "#"+e[s] ).val();
element.links = $( "#"+e[s] ).val();
items.push(element);
}
c = JSON.stringify(items);
e object source:
'0' => "resim" '1' => "baslik" '2' => "icerik" '3' => "link"
c object source:
[
{"resim":"4","baslik":"4","icerik":"4","links":"4"},
{"resim":"4","baslik":"4","icerik":"4","links":"4"},
{"resim":"4","baslik":"4","icerik":"4","links":"4"},
{"resim":"4","baslik":"4","icerik":"4","links":"4"}
]
AlliterativeAlice
12.7k9 gold badges56 silver badges73 bronze badges
-
2What is the expected result? Can you please describe what you're trying to achieve, so we here can help?TaoPR– TaoPR2015年06月07日 05:22:55 +00:00Commented Jun 7, 2015 at 5:22
2 Answers 2
You only ever store a single object in element
Each time you go around the loop you edit the existing object and then push another reference to it onto the array.
Create a new object each time you go around the loop.
for(s=0;s < e.length ; s++ ){
element = {};
answered Jun 7, 2015 at 5:26
Quentin
949k137 gold badges1.3k silver badges1.4k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You aren't creating a new object every time you push to the array, so you're just modifying the same object and pushing it into the array 4 times. You need to create a new object each time you loop through like so:
var e = [];
var data = [];
var items = [];
e = getelement("alan");
for(s=0;s < e.length ; s++ ){
var element = {};
element.resim = $( "#"+e[s] ).val();
element.baslik = $( "#"+e[s] ).val();
element.icerik = $( "#"+e[s] ).val();
element.links = $( "#"+e[s] ).val();
items.push(element);
}
c = JSON.stringify(items);
answered Jun 7, 2015 at 5:27
AlliterativeAlice
12.7k9 gold badges56 silver badges73 bronze badges
Comments
lang-js