I have an array that the values range from A to Z, which I want to convert to variables that depend on the input data, for example:
enter the data
362,232,113 and this becomes an array of a length of 3 unit.
so I want to assign the name of a variable depending on the length of the input array but when executing the code, it assigns the array index well, but that same index executes the length of the input array and does not assign the variables as I would like it to.
in fact when executing this happens:
(3) 326
showing that the matrix was correctly divided but the same index was executed 3 times, in summary what I want is to be executed as follows:
"A = 326" "B = 232" "C = 113"
In advance I thank you for your help
var asignLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","Z","X","Y","Z"];
matrix =[326,232,113];
function divide(){
xyz = matrix.split(",");
console.log(matrix);
for(var i = 0;i < xyz.length; i++){
window[assignLetter[i]] = xyz[i];
console.log(A); //(2) 326
}
}
You have a typo assignLetter instead of asignLetter ( two s ) and you need to pass a string to your function for it to work :
var assignLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","Z","X","Y","Z"];
divide("326,232,113")// input data
function divide(matrix){
xyz = matrix.split(",");
for(var i = 0;i < xyz.length; i++){
window[assignLetter[i]] = xyz[i];
}
}
console.log({A,B,C});
You should avoid creating global variabels like that, have them in an object instead
var assignLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","Z","X","Y","Z"];
var myVars = {};
divide("326,232,113")// input data
function divide(matrix){
xyz = matrix.split(",");
for(var i = 0;i < xyz.length; i++){
myVars[assignLetter[i]] = xyz[i];
}
}
console.log(myVars);
I think you want to pass the parameters 326,232,113 as a whole string. You're passing them as parameters wrong.
So just do the same thing you're doing but like this: divide("326,232,113")
I want to create an object by iterating through another one, and essentially appending to that new object.
So the issue at the moment is that the loop finishes with the final value of desiredData = JSON.parse(row[i]["Results"]) being added to the object i times. We should have i different objects added.
That is scoreObjectToSend[desiredUserId] contains the same object for all desiredUserId's.
I've tried using promises and some other JavaScript methods but to no use.
What I require is a loop over users, that adds their data to an object Object.
let raceData = {};
let desiredData = {};
let actualRaceString = raceArray[raceIndex]; // raceIndex defined earlier
let numberOfUsers = row.length; // row defined earlier
let i;
for (i = 0; i < numberOfUsers; i++) {
let desiredUserId = row[i]["Usernames"];
let desiredData = JSON.parse(row[i]["Results"]);
raceData[actualRaceString] = desiredData;
scoreObjectToSend[desiredUserId] = raceData;
}
Currently, I have an empty new object and I want to populate values from an existing object to new object because I want to use an object with only limited properties from the existing object (e.g. I only want the four properties instead of eight).
Here's how I am doing the mapping so far:
const newObject: any = {};
for (let i = 0; i < this.PRODUCT_DATA.length; i++) {
newObject._productSkuKey = this.PRODUCT_DATA[i]._productSkuKey;
newObject._storeKey = this.itemPriceForm.get('location').value;
newObject._price = this.PRODUCT_DATA[i]._price;
newObject._status = this.PRODUCT_DATA[i]._isActive;
this.updatedProducts.push(newObject);
}
So far, it looks to be storing the values from the existing object to newObject. However, it is only saving the last object values and not the different values from the object. How can I fix this to save all values (not just the last values for every object in the array)?
You need to make a copy of that before pushing in array
const newObject: any = {};
for (let i = 0; i < this.PRODUCT_DATA.length; i++) {
newObject._productSkuKey = this.PRODUCT_DATA[i]._productSkuKey;
newObject._storeKey = this.itemPriceForm.get('location').value;
newObject._price = this.PRODUCT_DATA[i]._price;
newObject._status = this.PRODUCT_DATA[i]._isActive;
this.updatedProducts.push(Object.assign({}, newObject));
// Or
// this.updatedProducts.push({ ...newObjec });
}
Or Simply create object inside loop. I love to use Array.prototype.forEach and Array.prototype.map
this.updatedProducts = this.PRODUCT_DATA.map(({_productSkuKey, _price, _isActive})=> ({
_productSkuKey,
_storeKey: this.itemPriceForm.get('location').value,
_price,
_status: _isActive
});
Avoid declaring newObject as 'const'. This is an updated code that works for me.
//avoid using a const, as you cannot override it
let newObject: any = {};
for (let i = 0; i < this.PRODUCT_DATA.length; i++) {
newObject._productSkuKey = this.PRODUCT_DATA[i]._productSkuKey;
newObject._storeKey = this.itemPriceForm.get('location').value;
newObject._price = this.PRODUCT_DATA[i]._price;
newObject._status = this.PRODUCT_DATA[i]._isActive;
this.updatedProducts.push(newObject);
//after pushing the object, empty all the current contents
newObject={};
}
How can I access the value for name in the object below? Also, does this object have a special name since unique keys (i.e. friend1 and friend2) hold other key/value pairs?
var friends = {
"friend1":{
"name":"ana",
"position":1,
"spouse":"billy"
},
"friend2":{
'name':'keri',
'position':2,
'spouse':'david'
}
};
Please note that this is a simplified version of the project I am working on. I realize there is a better way to hold data for a list of friends– the point to keep in mind is that the key that holds the other key/value pairs is unique.
I have tried this but it obviously does not work (i.e. "undefined"):
for( i = 0; i < Object.keys(friends).length; i++ ) {
var theFriend = [i].name;
alert(theFriend);
}
Here is a fiddle.
for(index in friends ) {
var theFriend =friends[index].name;
alert(theFriend);
}
Maestro please: https://jsfiddle.net/rwoukdpf/
In ES5, use:
for (var index in friends) { // NB: index and name have function scope
var name = friends[index].name;
}
In ES6, use:
for (let friend of friends) { // NB: 'of', not 'in'
let name = friend.name;
}
If you must use a normal for loop, ensure that your loop invariants are not evaluated in each iteration:
var keys = Object.keys(friends);
for (var i = 0, n = keys.length; i < n; ++i) {
var name = friends[i].name;
}
Even then this loop is not recommended, though - it's cheaper to use a single pass of the object with for .. in than to create an array of the keys and then iterate through that. The ES6 for .. of is better still.
Try following
var keys = Object.keys(friends);
for( i = 0; i < keys.length; i++ ) {
var theFriend = friends[keys[i]].name;
alert(theFriend);
}
For reference - https://jsfiddle.net/mu7jaL4h/7/
`[i]`
You've just created a new array and put the value of i in it.
You need to tell JavaScript what object you are accessing the i property of.
friends[Object.keys(friends)[i]].name
I have to iterate through an array, change one of its values, and create another array refelecting the changes.
this is what I have so far:
JS:
var arr = new Array();
arr['t1'] = "sdfsdf";
arr['t2'] = "sdfsdf";
arr['t3'] = "sdfsdf";
arr['t4'] = "sdfsdf";
arr['t5'] = "sdfsdf";
var last = new Array();
for (var i = 0; i <= 5; i++) {
arr['t2'] = i;
last.push(arr);
}
console.log(last);
Unfortunately, these are my results
As you can see, I am not getting the results needed as 0,1,2.. instead I am getting 2, 2, 2..
This is what i would like my results to be:
How can I fix this?
You have to make a copy, otherwise you are dealing with reference to the same object all the time. As it was said before - javascript does not have associate arrays, only objects with properties.
var arr = {}; // empty object
arr['t1'] = "sdfsdf";
arr['t2'] = "sdfsdf";
arr['t3'] = "sdfsdf";
arr['t4'] = "sdfsdf";
arr['t5'] = "sdfsdf";
var last = new Array();
for (var i = 0; i <= 5; i++) {
var copy = JSON.parse(JSON.stringify(arr)); //create a copy, one of the ways
copy['t2'] = i; // set value of its element
last.push(copy); // push copy into last
}
console.log(last);
ps: you can use dot notation arr.t1 instead of arr['t1']
The array access with ['t2'] is not the problem. This is a regular JavaScript feature.
The problem is: You are adding the SAME array to "last" (5 times in code, 3 times in the screenshot).
Every time you set ['t2'] = i, you will change the values in "last" also, because they are actually just references to the same array-instance.
You must create a copy/clone of the array before you add it to "last".
This is what will happen in all languages where arrays are references to objects (Java, C#...). It would work with C++ STL though.