javascript object reference by array - javascript

How can I refer to an object element dynamically during a loop by using an array, something like this:
var obj = {};
var lvl = ['x','y','z'];
var ol = [];
for (var l in lvl){
ol.push( lvl[l] )
obj[ol] = 'someval'
}
so where the reference may be obj[x][y][z] so each time the loop iterates, an additional key reference is appended, but I do not know how many levels there will be.
Not sure if I have explained that very well ?!

Based on how you answered my comment I believe this code will provide the nested object structure you are looking for.
var obj = {};
var lvl = ['x','y','z'];
var ol = {};
for (var i = 0; i < lvl.length; i++){
obj[i] = {};
ol = obj[key];
}

You mean you want someval to be the value of obj.x.y.z? You can always refer to the newly created levels using a variable:
var obj = {};
var levels = ['x','y','z'];
var pointer = obj;
for (var l=0; l<levels.length; l++) {
key = levels[l];
if (l < levels.length-1) { // if not last element
pointer[key] = {};
pointer = pointer[key];
}
else { // if last element
pointer[key] = 'someval';
}
}
console.log(obj); // should log {x:{y:{z:"someval"}}}

Related

Array of objects contains same object over and over again

I create multiple objects and push them to the array objArr:
var objArr = [];
var obj = {};
var height = [9,8,7,3,6,5,2,4];
for (var i = 0; i < 8; i++) {
debugger;
var mountainH = height[i];
obj.h = mountainH;
obj.index = i;
objArr.push(obj);
}
for (var i = 0; i < objArr.length; i++) {
alert(objArr[i].h);
}
But as you can see, each object has the same values. Why?
Put the initialization of obj within your for-loop.
You were re-assigning new values to a global variable obj.
var objArr = [];
var height = [9,8,7,3,6,5,2,4];
for (var i = 0; i < 8; i++) {
debugger;
var obj = {};
var mountainH = height[i];
obj.h = mountainH;
obj.index = i;
objArr.push(obj);
}
for (var i = 0; i < objArr.length; i++) {
console.log(objArr[i].h);
}
Because the scope of obj in your code is global and it should rather be contained in the for loop.
If you will not declare it inside the loop then the value will get overwritten of the same obj on each iteration instead of a new memory allocation.
var objArr = [];
var height = [9, 8, 7, 3, 6, 5, 2, 4];
for (var i = 0; i < 8; i++) {
debugger;
var mountainH = height[i];
var obj = {};
obj.h = mountainH;
obj.index = i;
objArr.push(obj);
}
console.log(obj);
As noted, you need to initialize a new object in each iteration of the loop, otherwise all your array members simply share the same object reference.
Additionally, your code can be greatly reduced by building the array using .map(), and fully using the object literal initializer to declare the properties.
var height = [9,8,7,3,6,5,2,4];
var objArr = height.map((n, i) => ({h: n, index: i}));
console.log(objArr);
This is shorter and clearer. For every number in height, it creates a new object and adds it to a new array, which is returned from .map().
It can be even a little shorter with the newer features for object literals.
var height = [9,8,7,3,6,5,2,4];
var objArr = height.map((h, index) => ({h, index}));
console.log(objArr);

Array appending after each onclick and loop in javascript

This is the code fragment I have tried:
radio.onclick = function() {
var pp = e.target.result.split("\n");
var pq = pp.split('\n');
var pr = []; // array to append each values
for (var k = 0; k < pq.length; k++) {
var a = pq[0];
}
pr = a; // I need to create an array which should append again and again
}
In this code, after clicking a radio, a loop generates the value for the 'a' variable, whom it's added to array 'pr'. I want to add the generated value to 'pr' itself after the next on-click.
Is it possible?
Just define the array
pr
globally.
var pr = []; // array to append each values
radio.onclick = function() {
var pq = pp.split('\n');
for (var k = 0; k < pq.length; k++) {
var a = pq[0];
}
pr.push(a); // i need to create an array which should append again and again
}
But there you just get the last pq[0]of the loop
Hope that helps
You probably want to do this:
radio.onclick = function() {
var pq = pp.split('\n');
var pr = []; // array to append each values
for (var k = 0; k < pq.length; k++) {
pr.push(pq[k]);
}
}
If you need global access to pr just define it outside from radio.onclick.
Edit
even shorter:
radio.onclick = function() {
var pq = pp.split('\n');
}
or global
var pq = [];
radio.onclick = function() {
pq = pp.split('\n');
}
$(document).ready(function(){var array = new Array(); //Global declaration
radio.onclick = function(){
//do stuff here..
//get your value
array.push(your value);
}
});
//if you want to clear the array
array.splice();

JavaScript for loop closure issue

I am adding all categories after ticking them to true if they exists in selected categories of result but it combines previous categories results with current one. I tried closure but it doesn't give me fresh object. Check out fiddle.
var allCatsResult = [{"id":1},{"id":2}, {"id":3}, ... ];
var catsArray = [1, 2] // Array of ids from allCatsResult
var result = [
{"id":1, selectedCategories:[{"id":1},{"id":2}]},
{"id":2, selectedCategories:[{"id":4},{"id":5}]},
...
];
for (var i = 0; i < results.length; i++) {
var tmp = allCatsResult; // tried to add function form here didn't work
for (var k = 0; k < results[i].selectedCategories.length; k++) {
var index = catsArray.indexOf(results[i].selectedCategories[k].category_id);
if(index !== -1) {
tmp[index].ticked = true;
}
}
results[i].categories = tmp;
}
Above code gives combined result for ticked = true for all categories in each result.
You need to copy/clone the array of objects, or you're manipulating the original. There are a few ways apparently. I chose the following:
var tmp = JSON.parse(JSON.stringify(allCatsResult));
This will create a new array of objects in tmp, and it will correctly only modify the clone.

Associative Arrays - Javascript

I am trying to populate an associative array, in a dynamic way. I have been reading a lot of documents but unable to figure out the right way.
The outcome of the code will be
op{
'0': value1, value2
'128': value3, value4, value 6
'630': value7
}
This is what i have written and is not working
var arr = [];
for(var i = 1; i <=last ; i++){
var key = rec[i].op;
var op = {};
op[key] = rec[i].description;
arr.push(op);
}
The most recent record is overwriting the previous record.
I think you want something like:
var op = {};
for(var i = 0; i < last ; i++)
{
var key = rec[i].op;
if (op[key] == undefined)
{
op[key] = [];
}
op[key].push(rec[i].description);
}

Creating objects in for loop. I missing the mark a bit

I would like to have a for loop create objects as the children of a parent object. Usually, I would declare the object without using the for loop like this:
var mObj = {};
mObj.obj1 = {};
mObj.obj2 = {};
mObj.obj3 = {};
mObj.obj3.firstname = "john";
mObj.obj3.lastname = "superfly";
Now lets say I would like to employ a for loop to create the children objects of a parent object "mObj".
This is where I am going wrong:
var mArr = ["firstname","lastname","email"]; // This array holds the keys for the objects
var mObj = {};
var len = (mArr.length);
for(var i=0; i<len; i++){
var obj+i = {}
mObj = obj+i;
mObj.obj + i.mArr[i] = ""
}
So the outcome of this would be:
mObj.obj1.firstname = "";
mObj.obj2.lastname = "";
mObj.obj3.email = "";
I just cannot seem to name the object with counter that is being created within for loop like:
obj1
obj2
obj3
Any help would highly be appreciated.
Thanks.
var obj+i = {} is invalid syntax.
Try this:
mObj['obj' + i] = {};
If i == 1, this gives
mObj['obj1'] = {};
Which is equiavlent to:
mObj.obj1
But when constructing dynamically, you have to use the
mObj['obj' + i]
Formatting.
var mArr = ["firstname","lastname","email"],
mObj = {},
len = (mArr.length),
i = 0;
for(; i<len; i++){
myObj['obj' + i] = {}
myObj['obj' + i].mArr[i] = ""
}
You need to use the bracket syntax to assign a dynamic variable. For example:
var sampleObj = {};
for(var j = 0; j < 3; j++)
{
sampleObj["obj" + j] = { test: j };
}
This should produce the following object:
{
"obj1" : { test: 1 },
"obj2" : { test: 2 },
"obj3" : { test: 3 }
}
After running the loop then, you could validly use this statement:
var testVal = sampleObj.obj1.test;

Categories

Resources