0

I am appending server sent data to table, showing selected/nested object attributes. I am facing difficulty in providing correct multi-dimensions to fetch correct data member.

Scenario: I'm having a json object, whose properties I need to fetch inside JavaScript. Script key (say, 'student.course.name') any length long member access hierarchy.

input: "student.course.name"
To be used as: someObject['student']['course']['name']
possible input keys: "age", "dept.name", "student.college.university.name" etc.

I've tried .split() and for loop but none fulfills all the possible requirement. Please suggest changes!

masT
  • 804
  • 4
  • 14
  • 29
  • 1
    Do you actually have the item as object in JavaScript? Or is it a string, separated by `.` that you wish to convert to an array? Your question isn't very clear. – BenM Jan 21 '14 at 10:22
  • *"I'm having a `json` object..."* It's just an object. You have have the object because you parsed JSON text, but once that text is parsed, it's just an object. – T.J. Crowder Jan 21 '14 at 10:31
  • possible duplicate of [JS reference multi-layered dynamic object string](http://stackoverflow.com/questions/18964074/js-reference-multi-layered-dynamic-object-string) – Evan Trimboli Jan 21 '14 at 10:32

1 Answers1

4

If you really have the string "student.course.name and you really have an object that has a property called student, which in turn has a property called course, which in turn has a property called name, e.g.:

var key = "student.course.name";
var someObject = {
    student: {
        course: {
            name: "the name"
        }
    }
};

Then this works:

var keys = key.split(".");
console.log(someObject[keys[0]][keys[1]][keys[2]]);

Live Example | Source

Or the indefinite-depth version:

var keys = key.split(".");
var value = someObject;
var n;
for (n = 0; n < keys.length; ++n) {
    value = value[keys[n]];
}
console.log(value);

Live Example | Source

We start with value = someObject, and for each key, we grab the relevant property from value and assign it to value. So on the first pass, value becomes the student object; on the second pass, it's course; and on the third and final pass, it's the value of name.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875