updating javascript object key value - javascript

If i try to add more keys with values to a javascript object it alters the value of all keys, not just the one I have added.
var corridorObject = {};
var makeObjects = [];
function someFunction(){
var a = makePoints;
var Corridor = viewer.entities.add({
corridor : {
positions : (a),
width : 10.0,
material : Cesium.Color.GREEN,
}
var idv0 = Corridor.id
corridorObject[idv0] = makeObjects;
console.log(corridorObject);
makeObjects.length=0;
}
The Corridor ID is a guid, the makeObjects an array of objects, when I run this it adds the key perfectly, and the values, but when I run it a second time it adds a new key with the new ID and new values, but it also changes the values for all the other keys to the most recent values.
here is the console, as you can see the first time the array for the ID is 3 long the second time with the same id its 2 long
Object {91ff9967-7019-4e76-846e-c0e125481060: Array[3]}
Object {91ff9967-7019-4e76-846e-c0e125481060: Array[2], 3de2c2b1-5fb6-495c-9034-2b37713e5c30: Array[2]}
Sorry to be more clear, this is from Cesiumjs, its taking points and converting them to a corridor, the corridor id and an array of the points that made it are then added to this object. The array of points is then emptied.

If you are repeating
var corridorObject = {};
var makeObjects = [];
var idv0 = Corridor.id
corridorObject[idv0] = makeObjects;
console.log(corridorObject);
These line of code then It will initialise
var corridorObject = {};
Thats why you will get only one key. Put initialization outside of the iteration

Related

For Loop only adds same object every time instead of different object properties

I am writing a for loop that is iterating over an array which contains different lines in a text document.
Each iteration I am trying to pull certain parts of each of the text data lines and add them to an object, namely localinoData.
At the end of each iteration I am trying to add the localinoData object (with each object property set to a new one) to a new array.
When just adding the string found in each line the to data array (localinoDataObjArray) I get different values for each of the array. However when I now change the localinoData object properties on each iterations and try to append that changed object to the array, i get the same object in all of the array positions, e.g when I
alert(localinoDataObjArray[x].X_COORD);
for all values of x, the X_COORD is the same.
function GetlocalinoDataFromFile(localinoDataFile){
var localinoDataObjArray = new Array();
var localinoData = {
time: null,
tagID: null,
X_COORD: null,
Y_COORD: null,
Z_COORD: null,
};
var allData = localinoDataFile.responseText;
var arrayOfDataLines = allData.split('\n');
// for each iteration, get the tagID, and the co-ords(seperate) and then
// create a localinoData object and add to array
for (var i = 0; i < arrayOfDataLines.length; i++) {
if (/tag: [0-9]{22}/.test(arrayOfDataLines[i])) {
var tagID = /tag: [0-9]{22}/.exec(arrayOfDataLines[i]);
localinoData.tagID = tagID;
}
if (/[0-9]+.[0-9]{3}, [0-9]+.[0-9]{3}, [0-9].[0-9]{3}/.test(arrayOfDataLines[i])) {
XYZ_COORDS = /[0-9]+.[0-9]{3}, [0-9]+.[0-9]{3}, [0-9].[0-9]{3}/.exec(arrayOfDataLines[i]);
temp = XYZ_COORDS.toString();
temp2 = temp.split(', ');
// Here I am changing the object to new values each loop
localinoData.X_COORD = temp2[0];
localinoData.Y_COORD = temp2[1];
localinoData.Z_COORD = temp2[2];
}
// Here I am appending the newly changed object to my array
// however the same object is being added every time
// (which corresponds to the last line in the text document)
localinoDataObjArray.push(localinoData);
}
// the object values for localinoDataObjArray[0]
// and localinoDataObjArray[50] are the exact same
alert(localinoDataObjArray[20].X_COORD);
}
I expect all of the array values to be different corresponding to the different lines in the text document. However all of the array values are the same (which equal the expected result of iteration over the last line in the text document).
I am very confused as when i = 0, it should be adding an object that has the values of the first line in my text document, however it shows the values i would expect from the last line in the document.
This is very strange to me and seems like a looping problem? I am very confused and would appreciate any help in this matter.
They are all references to the same object which you keep overwriting.
Try and make a fresh instance of localinoData in every iteration of your for loop.
function GetlocalinoDataFromFile(localinoDataFile){
var localinoDataObjArray = new Array();
var allData = localinoDataFile.responseText;
var arrayOfDataLines = allData.split('\n');
// alert(arrayOfDataLines[4]);
// for each iteration, get the tagID, and the co-ords(seperate) and then create a localinoData object and add to array
for (var i = 0; i < arrayOfDataLines.length; i++) {
var localinoData = {
time: null,
tagID: null,
X_COORD: null,
Y_COORD: null,
Z_COORD: null,
};
if (/tag: [0-9]{22}/.test(arrayOfDataLines[i])) {
var tagID = /tag: [0-9]{22}/.exec(arrayOfDataLines[i]);
localinoData.tagID = tagID;
}
if (/[0-9]+.[0-9]{3}, [0-9]+.[0-9]{3}, [0-9].[0-9]{3}/.test(arrayOfDataLines[i])) {
XYZ_COORDS = /[0-9]+.[0-9]{3}, [0-9]+.[0-9]{3}, [0-9].[0-9]{3}/.exec(arrayOfDataLines[i]);
temp = XYZ_COORDS.toString();
temp2 = temp.split(', ');
localinoData.X_COORD = temp2[0];
localinoData.Y_COORD = temp2[1];
localinoData.Z_COORD = temp2[2];
}
localinoDataObjArray.push(localinoData);
}
alert(localinoDataObjArray[20].X_COORD);
}

My variables wont save in the array, they get replaced? help me

I am trying to save my variables in an array. Theses variables are written in by the user and saved to localStorage when a button is pressed. On my other html page i reach these variables and put them in 3 different arrays(the variables, that go in three arrays). Then the user writes in new text and save to the variables. Now to the problem. The newly created variables don't add to the array, they replace. I'm thinking this is due to to the same variable name however I can't find an solution.
I have tried to change variable names etc for saving the new variable but cant find solution.
//This is html page 2 (gets the items from localhost)
var TankaKostnadVar = localStorage.getItem("StorageKostnadVar");
var TankaLiterVar= localStorage.getItem("StorageLiterVar");
var TankaDatumVar = localStorage.getItem("StorageDatumVar");
var arrayKostnad = [];
var arrayLiter = [];
var arrayDatum = [];
arrayKostnad.push(TankaKostnadVar,);
arrayLiter.push(TankaLiterVar,);
arrayDatum.push(TankaDatumVar,);
document.write(arrayLiter,arrayKostnad,arrayDatum); //Ignore this, just test
//This is the code where the user is writing and it saves to localStorage.
//Html page 1 that saves the variables
var TankaKostnadVar = document.getElementById("tankaKostnad").value;
var TankaLiterVar = document.getElementById("tankaLiter").value;
var TankaDatumVar = document.getElementById("tankaDatum").value;
localStorage.setItem("StorageKostnadVar", TankaKostnadVar);
localStorage.setItem("StorageLiterVar", TankaLiterVar);
localStorage.setItem("StorageDatumVar", TankaDatumVar);
I expect the array to add the variable. So if the user writes an 5 the array should first be [5] then when the user writes an 8 the array should be [5,8]
If you don't want use JSON, you can save string comma separated and, when necessary, transform the items to numbers. To transform in numbers you can use map function or a for. Localstorage only save strings, so if you need to be back to numbers you need to use JSON.parse or use function parseInt, that is global.
//Retrieve saved items from localstorage
var TankaKostnadVar = localStorage.getItem("StorageKostnadVar"); // "1,2"
var TankaLiterVar = localStorage.getItem("StorageLiterVar");
var TankaDatumVar = localStorage.getItem("StorageDatumVar");
TankaKostnadVar += "," + document.getElementById("tankaKostnad").value;
TankaLiterVar += "," + document.getElementById("tankaLiter").value;
TankaDatumVar += "," + document.getElementById("tankaDatum").value;
localStorage.setItem("StorageKostnadVar", TankaKostnadVar);
localStorage.setItem("StorageLiterVar", TankaLiterVar);
localStorage.setItem("StorageDatumVar", TankaDatumVar);
// if you want to transform TankaKostnadVar and others two, just do like this
TankaKostnadVar.split(','); // result: ['1', '2']
// if you want to transform to number
TankaKostnadVar = TankaKostnadVar.split(',').map( function(number) {
return parseInt(number)
} );
The split function of string, breaks a strings in parts separated by one string. In this case, breaks a string separated with comma. So "1,2" turns into ['1', '2'].
If you want to keep adding to the array you'll need to push the entire array you're holding in memory up to localStorage after appending a new element. Alos, localStorage only stores string values so if you want to maintain the Array structure you'll have to use JSON.stringify() before running setItem() and then JSON.parse() next time you access those values with getItem().
//This is the code where the user is writing and it saves to localStorage.
//Html page 1 that saves the variables
var TankaKostnadVar = document.getElementById("tankaKostnad").value;
var TankaLiterVar = document.getElementById("tankaLiter").value;
var TankaDatumVar = document.getElementById("tankaDatum").value;
localStorage.setItem("StorageKostnadVar", JSON.stringify( [TankaKostnadVar] ));
localStorage.setItem("StorageLiterVar", JSON.stringify( [TankaLiterVar] ));
localStorage.setItem("StorageDatumVar", JSON.stringify( [TankaDatumVar] ));
//This is html page 2 (gets the items from localhost)
var TankaKostnadVar = localStorage.getItem("StorageKostnadVar");
var TankaLiterVar = localStorage.getItem("StorageLiterVar");
var TankaDatumVar = localStorage.getItem("StorageDatumVar");
var arrayKostnad = JSON.parse(TankaKostnadVar);
var arrayLiter = JSON.parse(TankaLiterVar);
var arrayDatum = JSON.parse(TankaDatumVar);
// Now you have arrays with data, but I don't know what you want to do with them...
// you could add more values like this (still page 2)...
arrayKostnad.push('new value 1')
arrayLiter.push('new value 2')
arrayDatum.push('new value 3')
localStorage.setItem("StorageKostnadVar", JSON.stringify( arrayKostnad ));
localStorage.setItem("StorageLiterVar", JSON.stringify( arrayLiter ));
localStorage.setItem("StorageDatumVar", JSON.stringify( arrayDatum ));
// now check the values again
var TankaKostnadArr = JSON.parse(localStorage.getItem("StorageKostnadVar"));
var TankaLiterArr = JSON.parse(localStorage.getItem("StorageLiterVar"));
var TankaDatumArr = JSON.parse(localStorage.getItem("StorageDatumVar"));
document.write(TankaKostnadArr, TankaLiterArr, TankaDatumArr)
And this is what I would do to clean things up a little...
// Import these functions and variables to any file that needs to interact with LocalStorage
var storageKeys = ["StorageKostnadVar","StorageLiterVar","StorageDatumVar"];
function addToArray(key, val, arrObj) {
arrObj[key].push(val)
}
function storeAllLocalStorage(arrayObject) {
Object.keys(arrayObject).forEach(key=>{
localStorage.setItem(key, JSON.stringify(arrayObject[key]));
})
}
// Use above functions when needed
var storedArrays = storageKeys.reduce((acc,key)=> {
var val = JSON.parse(localStorage.getItem(key));
if (typeof val === 'array') return {...acc, [key]:val};
return {...acc, [key]:[val]};
},{})
addToArray("StorageKostnadVar", document.getElementById("tankaKostnad").value, storedArrays);
addToArray("StorageLiterVar", document.getElementById("tankaLiter").value, storedArrays);
addToArray("StorageDatumVar", document.getElementById("tankaDatum").value, storedArrays);
storeAllLocalStorage(storedArrays)
You are simply using localStorage.setItem which saves your values with the given key. If the key exists, it will replace the value. Before you do a .setItem, get the value from the local storage first, then parse it to array so that you can finally push the new user inputs to that parsed array. Then you can .setItem to replace the "outdated" value from the localStorage.
UPDATE Example:
Sorry for leaving this hangin without an example. Here it is:
// Get array from local storage
const stringifiedArray = localStorage.getItem('myCollection');
// If there is no 'myCollection' from localStorage, make an empty array
const myCollection = stringifiedArray ? JSON.Parse(stringifiedArray) : [];
myCollection.push('My new item added'); // update array
localStorage.setItem('myCollection', JSON.stringify(myCollection)); // save

Duplicate an array in an object then update a value based on key - Javascript

I need help doing the following.
I need to duplicate an array, update a value and insert it into a new object.
My Code right now:
// Sample test values {name:'The initial value', altName:'a first Name;a second name'}
var allAltName = test.altName;//Test come from a forEach() Iteration
if (test.altName) {//First I check if ther is my parama altName
var b,
countAllAltName = allAltName.split(';'); //Here I split my parameter string based on ';'
if (countAllAltName.length > 0) {
for (b = 0; b < countAllAltName.length; b = b + 1) {
var originalName = {};//I create a new object
originalName = test;//I load my existing object into a blank object
if (!ret["Index"]) // I check if my final object Key exist
ret["Index"] = {}; // if not create new object
if (!ret["Index"]["Index"]) // check another key
ret["Index"]["Index"] = []; // if not create new
originalName.name = countAllAltName[b];//Update my new object originalName with new value
ret["Index"]["Index"].push(originalName); // push current element in the designated list
ret["Index"]["Index"].sort(function (a, b) {
return a.name.localeCompare(b.name);
});
console.log(ret);
}
}
}
Issue is ret contains the required Object keys,but all value of name in each aray have the same last value of altName
I console.log() at each step what is the value of originalNameit always looks good.
Why the end results failed, and where I'm overwriting my data.
When you write originalName = test, you tell to JS that originalName is an "alias" for test (both share the same reference).
The behaviour is what you change in originaleName, it's impacted in test and vice versa (behaviour true only for Array and Object).
If you want to do a real copy, the simplest way (but with restrictions) is :
originalName = JSON.parse(JSON.stringify(test));
Last things : var originalName = {} is not an Array but an Object. There are some important differences between them

Empy array values are created when adding to array

I have the below code:
var changes = new Array();
$(".item_prices").on("blur", function(){
var item_id = $(this).attr("id");
var item_price = $(this).html();
changes[item_id] = item_price;
});
Every time a new value is entered, I want to save the item's ID as the key and its price as the value. If I save items with IDs 4 and 6 and prices 1.99 and 2.99, respectively, I get the following array:
{,,,,1.99,,2.99}
How do I add to the array without incurring empty values?
Use object, not Array:
var changes = {};
The rest is the same.
Key-value should always be saved in an object.
Since you're using jQuery, here is another answer to an unasked question,
Use native javascript functions when it's possible and simple, specially when it's even simpler:
var item_id = $(this).attr("id");
var item_price = $(this).html();
Can and should be:
var item_id = this.id
var item_price = this.innerHTML;
You don't want an array, a simple object will form a collection of key value pairs for you:
var changes = {};
If / when the time comes to enumerate these changes:
for (var name in changes) {
if (changes.hasOwnProperty(name)) {
var value = changes[name];
...
}
}
Arrays are a special case of objects, whose elements have consecutive integer keys. You don't have consecutive keys, so Array is "filling the gaps" for you.
Use a barebones Object instead:
var changes = {};

Why couldn't i insert the same element into an array in javascript?

I have a array of objects. But when I insert the object the I previously added, it will override my previous object. how can I solve it?
I have on object called player. In player, I have two array : one called onHandWeapon, one called onFieldWeapon. They are array of weapon object.
function player(lp){
this.lp = lp;
this.onFieldWeapon = new Array();
this.onHandWeapon = new Array();
}
function weapon(id, heart, bullet, src){
this.id = id;
this.heart = heart;
this.bullet = bullet;
this.src = src;
this.location;
this.name;
this.discription;
this.bufferBullet = bullet;
}
I have set three dummy object in onHandWeapon array. Then I want to randomly pick up one of them and put it into onFieldWeapon and assign a random location to it.
function aiCreateWeapon(){
var b = Math.floor(Math.random()*ai.onHandWeapon.length);
$('#console').append(' ' + b + ' ');
var ip = 100;
while($('#'+ip).attr('class') != 'enemyField'){
ip = Math.floor(Math.random()*48);
}
encurrentWeapon = ai.onHandWeapon[b];
var source = encurrentWeapon.src;
var oImg = document.createElement("img");
oImg.setAttribute('src', source);
oImg.setAttribute('height', '60px');
oImg.setAttribute('width', '60px');
$('#'+ip).append(oImg).show('explode','slow');
encurrentWeapon.location = ip;
ai.onFieldWeapon.push( encurrentWeapon);
$('#console').append(' ' + ai.onFieldWeapon[0].location + ' ');
}
aiCreateWeapon is a function bind to a button. When I click it, the ai.onFieldWeapon[0].location is a fixed location until it changes. I have check that every time when the object which is same as the first element, is added to the onFieldWeapon Array, it will override the first element's data.
When you insert the same object into an array multiple times, you'll have multiple entries in the array that are all references to the same underlying object. In the following example all three entries in myArray and the x and y and myObj variables all point to the same underlying object, so if you change the properties of the object via one of the array items it's not that it updates the other array items too, it is that the other array items point to the same object you just changed:
var myObj = { "p1" : "v1", "p2" : "v2" };
var myArray = [];
// all of the following reference the same underlying object as myObj,
// not copies of myObj.
myArray.push(myObj);
myArray.push(myObj);
myArray.push(myObj);
var x = myObj,
y = myObj;
myArray[1].p1 = "new value";
alert(myArray[0].p1); // "new value"
alert(x.p1); // "new value"
It sounds like what you want to do is create a copy of the object each time so that each item in the array is an independent object that you can update without affecting all the others. Unfortunately there is no built-in way to do that in JavaScript. Fortunately it's not particularly difficult to write your own object copying function, especially in your case where you seem to have only a one-dimensional object:
function copyObject(srcObj) {
// create new blank object and copy the direct properties one by one
var newObj = {};
for (var k in srcObj)
if (srcObj.hasOwnProperty(k))
newObj[k] = srcObj[k];
return newObj;
}
var myObj = { "p1" : "v1", "p2" : "v2" };
var myArray = [];
// make independent copies instead of just more references to the same object
myArray.push(copyObject(myObj));
myArray.push(copyObject(myObj));
myArray.push(copyObject(myObj));
var x = copyObject(myObj),
y = copyObject(myObj);
myArray[1].p1 = "new value";
alert(myArray[0].p1); // "v1"
If you have objects that contain objects or arrays then your copyObject() function needs to be more complicated - usually some form of recursion would be used.

Categories