1

so i have an array like this:

var arr=[one, lol];

and an object like this

var obj={
    one:{
        lol:11234
    }
}

How do I make it so if i do obj[lol] then it will print out 11234? Keep in mind I don't know how long the array is and answers like console.log(obj[one][lol]) doesn't work. Thanks in advance.

eclipseIzHere
  • 83
  • 1
  • 7

4 Answers4

1

You can store the previous property's value (initially obj) and continue to loop until end of array like so:

var arr = ['one', 'two', 'three'];

var obj = {
  one: {
    two: {
      three: 11234
    }
  }
}

var currentProp = obj;

for(var i = 0; i < arr.length; i++) {
  currentProp = currentProp[arr[i]];
}

console.log(currentProp);

The above code will start at the object obj, then loop until the array's length, and reassign currentProp to the next property in the array as it goes. In this case, this is what it does:

  • First iteration, access obj[arr[0]], which is one, and assign it to currentProp
  • Second iteration, access obj[arr[0]][arr[1]] or one[arr[1]], which is two, and assign it to currentProp
  • Third iteration, access obj[arr[0]][arr[1]][arr[2]] or two[arr[2]], which is three, and assign it to currentProp. Loop then terminates as it has reached end of the list.

In the end, the value of the last property will be in currentProp, and will correctly output 11234.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
  • is there any way to make it so if i do obj[three] and it will return 11234? – eclipseIzHere Oct 17 '16 at 05:07
  • @eclipseIzHere No. Bracket notation looks for a prop of the object, it doesn't look for descendants or nested objects. You would have to manually traverse the object and search it. – Andrew Li Oct 17 '16 at 05:08
0

You need to try like this :

obj["one"]["lol"]

JsFiddle : https://jsfiddle.net/3we2ohy6/1/

Venkat
  • 2,549
  • 2
  • 28
  • 61
0

Since you are just looking up a property value it is simpler to do:

console.log(obj.one.lol);

Doing it using the square brackets the way you have it JS thinks both the one and LOL are variables. Unless you wrap them in quotes.

console.log(obj['one']['lol');

You will not get to the value you are looking for the way you are doing it unless you create a function that either restructures the obj object or you feed it the obj.one as a property.

andre mcgruder
  • 1,120
  • 1
  • 9
  • 12
0

You could use Array#reduce, because this returns the object you need, without keeping a reference outside.

function set(object, path, value) {
    var last = path.pop();

    path.reduce(function (o, k) {
        return o[k] = o[k] || {};
    }, object)[last] = value;
}

var obj = {};

set(obj, ['one', 'lol'], '11234'); 
   
console.log(obj);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392