mesqueeb
mesqueeb

Reputation: 6354

Add an existing var to a new object in JavaScript and loop through them

I find numerous guides on how to add variables to existing objects, but nowhere how to add an "existing" variable to an existing object.

I have a whole list with variables already defined in my script. e.g.: a, b, c, d. and they all have their own values. Now I want to call a function on all these variables and then show the variable-names and outcome in console. Therefor I want to create an object out of them to loop through. How do I do this?

This is my workflow: Values are created in various places in the script:

a = 1.333;
b = 1.64252345;
c = 2.980988;

I create the object and try to add the already existing variables (this is where I fail):

var abc = {};
abc.a;
abc.b;
abc.c;

I want to loop through the object, flooring all numbers, and printing the variable-name with the returned number:

var i;
for (i = 0; i < abc.length; ++i) {
    var variablename = Object.keys(abc[i]);
    var flooredvalue = floor(abc[i]);
    var abc[i] = flooredvalue; // Save the floored value back to the variable.
    console.log(variablename+": "+flooredvalue);
}

My desired output in console.log:

a = 1
b = 1
c = 2

Upvotes: 1

Views: 115

Answers (1)

rrk
rrk

Reputation: 15875

Looping through the array of object keys will be a good idea.

a = 1.333;
b = 1.64252345;
c = 2.980988;

var abc = {};
abc.a = a;
abc.b = b;
abc.c = c;

var i;
var keys = Object.keys(abc);
console.log(abc['a'])
for (i = 0; i < keys.length; i++) {
    var key = keys[i];
    var flooredvalue = Math.floor( abc[key] );
    abc[key] = flooredvalue;
    window[key] = flooredvalue; //global variable change.
}
console.log(a);
console.log(b);
console.log(c);

Upvotes: 2

Related Questions