Reputation: 27
I have an array with variables. I would like to push some x and y coordinates into the array, but when i try to push instead of changing the variable values the push creates new variables and assign the value to those.
So it looks like this
0: {id: "t523470", name: "tPm1", x: 0, y: 0, parent: null, …}
1: {id: "t523471", name: "tPm2", x: 0, y: 0, parent: null, …}
2: {y: 651, x: 446}
3: {y: 800.015625, x: 802.328125}
Instead of this
0: {id: "t523470", name: "tPm1", x: 446, y: 651, parent: null, …}
1: {id: "t523471", name: "tPm2", x: 802.328125, y: 800.015625, parent: null, …}
function getModulePosition(id) {
for (let i = 0; i < axisViewElements.modules.length; i++) {
let currentElement = axisViewElements.modules[i].id;
if (id === currentElement) {
continue;
}
let module = document.getElementById(currentElement);
let modulePos = { x: module.getBoundingClientRect().left, y: module.getBoundingClientRect().top }
console.log(modulePos);
axisViewElements.modules.push({
y: modulePos.y,
x: modulePos.x
});
}
}
Upvotes: 0
Views: 1190
Reputation: 16287
Try it here https://runkit.com/embed/pd68veqr5ey7
let input = [
{id: "t523470", name: "tPm1", x: 0, y: 0, parent: null},
{id: "t523471", name: "tPm2", x: 0, y: 0, parent: null}
];
let newValue = [
{y: 651, x: 446},
{y: 800.015625, x: 802.328125}
];
input.forEach((item, index) => item = Object.assign( item , newValue[index]));
console.log(input);
Upvotes: 1
Reputation: 4378
You are pushing to array which always creates a new element.
I'm assuming that your elements are unique inside array with respect to their id
attribute. So you have to find the element with the id
and then update the x
and y
attributes.
Your code will be like this:
elementToUpdate = axisViewElements.modules.find(el => el.id === you_id)
elementToUpdate.x = modulePos.x
elementToUpdate.y = modulePos.y
Upvotes: 1
Reputation: 73966
Array push
method always insert a new element into an array. As you need to update an existing element you can simply do this:
axisViewElements.modules[i].y = modulePos.y;
axisViewElements.modules[i].x = modulePos.x;
Upvotes: 1
Reputation: 241
Array.prototype.push always creates a new index with your values. You cannot use .push() and expect to change previous values in the Array. For your purpose you have to loop through your array, find the indexes you want to change some values in them and then assign your new values to them.
Upvotes: 1