Reputation: 4264
I have the below javascript which puts a list of customers into an object, then outputs then on the page.
var name = ["andrew", "vic", "casey"];
var job = ["builder", "baker", "dentist"];
var product = [111, 222, 111];
var qty = [1, 2, 3];
var data = {};
for (i = 0; i < name.length; i++) {
a = {
"name": name[i],
"job": job[i],
"product": product[i],
"qty": qty[i]
};
a['xtra-' + product[i]] = qty[i];
data[name[i]] = a;
console.log(a);
}
data = $.map(data, function (val, key) {
return val;
});
data.sort();
$.each(data, function (i, val) {
$('body').append(val.name + ' - ' + val.job + ' - ' + val.product + ' - ' + val.qty + ' - ' + (val.xtra + val.product) + '<br>');
});
With what I have so far see fiddle, I am outputting the persons name - job - product - qty.
andrew - builder - 111 - 1 - NaN<br>
vic - baker - 222 - 2 - NaN<br>
casey - dentist - 111 - 3 - NaN<br>
I am also trying to print out some extra information which is storred in my object called 'xtra-' + product[i].
This is being storred in a as you can see from the console log eg xtra-222 however, I can't get it outputting in my each statement? I understand what I have done
val.xtra + val.product
is trying to add a number with a string and this is why it isn't working but I can't seem to get work out what syntax is required (possibly getting the last nth item) here or maybe there is another method to acheive what I want here? In case there is any confusion I want my output to be
andrew - builder - 111 - 1 - 1
vic - baker - 222 - 2 - 2
casey - dentist - 111 - 3 - 3
Where the last 1,2,3 comes from the value 'xtra-' + product[i] stored in a
Upvotes: 3
Views: 80
Reputation: 1033
in your $.each did you mean
val["xtra-" + val.product]
?
Here is a working fiddle http://jsfiddle.net/p5Zhc/3/
Upvotes: 1
Reputation: 636
The problem is inside the .each loop, more specifically in (val.xtra + val.product)
.
The val object for the first run of that loop is:
Object {name: "andrew", job: "builder", product: 111, qty: 1, xtra-111: 1}
As you can see, there's no xtra key in that object, instead you have an xtra-111 key. So if you use (val['xtra-' + val.product] + val.product)
you'll get the result that you need.
Here's the fixed code http://jsfiddle.net/VdVax/
Upvotes: 2