javascript - How do I add (push) items to an array one at a time (looping through array) -
i can't figure weird problem out. link jsbin
i'm trying add values array (prices
), using click function. when user clicks button, adds pricing data javscript array prices
.
i need add multiple data entries @ once, contain price different day
.
this click function #add_pricing.
$("#add_pricing").click(function(e){ e.preventdefault(); data = { "price": "1200", "days": ["1","3","4"] } adddata(data); console.log(prices) });
so when user clicks that, can see sends data
variable adddata, is:
function adddata(data) { (i = 0; < data.days.length; i++){ data.day = data.days[i]; //eg. data.day = "1" prices.push(data); } }
so adddata()
function loops through data.days , want push entry prices
array, 1 @ time.
but instead seems push 4 items @ time every itteration (you can see if log output)
and doesn't set day variable properly, day set 4, though if log output, seems displaying correct one.
expected output:
[1] => {day: 1, price: 1200} [2] => {day: 3, price: 1200} [3] => {day: 3, price: 1200}
actual output
[1] => {day: 4, price: 1200} [2] => {day: 4, price: 1200} [3] => {day: 4, price: 1200}
you modifying day
property of data
on , on again. data
object never recreated.
did mean this?
function adddata(data) { (i = 0; < data.days.length; i++){ data.day = data.days[i]; //eg. data.day = "1" prices.push(data.day); // push data.day? } }
if want clone object, can use jquery's extend so. or if you're in node, extend module same thing.
function adddata(data) { (i = 0; < data.days.length; i++){ var newdata = $.extend({}, data); newdata.day = data.days[i]; //eg. data.day = "1" prices.push(newdata); } }
if object in real code simple 1 you've used in question, may easier create new object:
function adddata(data) { (i = 0; < data.days.length; i++){ prices.push({ price: data.price, day: data.days[i] }); } }
Comments
Post a Comment