Gardinero
Gardinero

Reputation: 331

Pushing objects to array

I have three html buttons on my page:

<button class="timespanbutton" value="1">1</button>
<button class="timespanbutton" value="2">2</button>
<button class="timespanbutton" value="3">3</button>

Now I want to create an array, containing an object for each button:

var timespanObject = {}, timespanArray = [];
countSpecificFacilitySlotAmount = 3;

$('.timespanbutton').each(function() {
 slotName = "timespanbutton" + $(this).val();
  timespanObject.timespanName = slotName;
    timespanArray.push(timespanObject);
});

to get an array containing 3 objects with each created name like

timespanbutton1
timespanbutton2
timespanbutton3

I really do not know, what I am doing wrong, but all three get the name

timespanbutton3

What am I doing wrong?

Upvotes: 0

Views: 68

Answers (2)

Kundan Singh Chouhan
Kundan Singh Chouhan

Reputation: 14282

You need to declare slotname variable in loop, it reference in context and having last value all time.

So try this instead

$('.timespanbutton').each(function() {
    var slotName = "timespanbutton" + $(this).val(); // new var declare
    var timespanObject.timespanName = slotName;
    timespanArray.push(timespanObject);
});

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

Well you are changing the reference of same object

Understand with example how it works

let a ={};
let b = a;
a.name = 'xyz';
a.name = 'abc';
console.log(a.name)
console.log(b.name)

So here in above example we have two variables a and b. a is an object.

  1. Every time we update name the last value will be overwritten by new one.
  2. When we assign a object to any other variable it is assigned as reference not a copy.So as we change the value of a you can see the change if you print b.

Working version of your code below

var timespanArray = [];
countSpecificFacilitySlotAmount = 3;

$('.timespanbutton').each(function() {
 slotName = "timespanbutton" + $(this).val();
 var timespanObject = {};
  timespanObject.timespanName = slotName;
    timespanArray.push(timespanObject);
});

console.log(timespanArray)
<script
			  src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
			  integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E="
			  crossorigin="anonymous"></script>
<button class="timespanbutton" value="1">1</button>
<button class="timespanbutton" value="2">2</button>
<button class="timespanbutton" value="3">3</button>

Upvotes: 1

Related Questions