Reputation: 886
I am stepping through a bunch of XML, trying to build an array within javascript.
XML:
<?xml version="1.0" encoding="utf8" ?>
<session>
<id>12</id>
<name>20130520105033-0-1</name>
<userid>0</userid>
<changed>2013-05-20 11:16:31</changed>
<till>1</till>
<custid>1</custid>
<details>
<item>
<prodcode>TRD3066</prodcode>
<qty>1</qty>
<tax>15</tax>
<uprice>23.1</uprice>
<price>1</price>
</item>
<item>
<prodcode>DIC72000280</prodcode>
<qty>1</qty>
<tax>15</tax>
<uprice>278.26</uprice>
<price>1</price></item>
<item>
<prodcode>KRE22208</prodcode>
<qty>1</qty>
<tax>15</tax>
<uprice>4.65</uprice>
<price>1</price>
</item>
</details>
<comment></comment>
<customer_comment></customer_comment>
</session>
Javascript used to parse this: (after passing the details xml tag)
function parse(details){
var ret=[];var tot=[];
jQuery(details).find("item").each(function(){
ret[0]= jQuery(this).find('prodcode').text();
console.log("parse "+ret[0]);
ret[1]= jQuery(this).find('qty').text();
ret[2]= jQuery(this).find('tax').text();
ret[3]= jQuery(this).find('uprice').text();
ret[4]= jQuery(this).find('price').text();
tot.push(ret);
console.log("tot="+tot);
});
return tot;
}
The problem console result is
parse TRD3066 tot=TRD3066,1,15,23.1,1 parse DIC72000280 tot=DIC72000280,1,15,278.26,1,DIC72000280,1,15,278.26,1 parse KRE22208 tot=KRE22208,1,15,4.65,1,KRE22208,1,15,4.65,1,KRE22208,1,15,4.65,1
It's one of those nights, and I am just not seeing why the end tot array is not all the individual items ??
Upvotes: 0
Views: 4436
Reputation: 7442
I think it is the .each
function that is causing the issue, you should replace it with simple for
loop
var items = jQuery(details).find("item");
for (var i = 0; i < items.length; i++) {
var ret = [];
ret[0] = jQuery(items[i]).find('prodcode').text();
console.log("parse " + ret[0]);
ret[1] = jQuery(items[i]).find('qty').text();
ret[2] = jQuery(items[i]).find('tax').text();
ret[3] = jQuery(items[i]).find('uprice').text();
ret[4] = jQuery(items[i]).find('price').text();
tot.push(ret);
console.log("tot=" + tot);
}
Upvotes: 3
Reputation: 18217
You are pushing a reference to the same ret array multiple times to tot, then changing the referenced ret array.
Also note that tot.push(ret) does not push each item from ret onto tot, rather it pushes a reference to ret to tot. When you change the contents of ret in the next round, it will look like every item in tot is changing, because they are all references to the same array.
Perhaps instead of tot.push(ret) you want to
tot.push(ret[0], ret[1], ret[2], ret[3], ret[4]);
Or don't make that ret array at all and instead just push individual texts as you get them.
Upvotes: 0