0

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?

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Bingo! This is the right answer, because it explains why it contains same names.
0

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.