1

Possible Duplicate:
Dynamic object property name

I want to dynamically generate access to an object's property.

If I try to access mydata[i].val.name I get somename.

If I try it like mydata[i] + bar[j] (where bar[j] === '.val.name') it fails.

How do I dynamically create something like this? So that I can access any property of an object using a user generated value?


Some code:

If I have an object I want to be able to iterate through its properties, gathering the ones I am interested in. Ideally I would like something like the following:

var processData = function (data, keys, values) {
  var returnData = [], i, j, k;
  var parsedData = JSON.parse(data);
  var keys = keys || null;
  var values = values || null;
  var datalen = parsedData.length;

  for (i = 0; i < datalen; i++) {
      returnData[i] = {};
      for(j = 0; j< keys.length; j++){
          for(k = 0; k < values.length; k++){
              returnData[i][keys[j]] = parsedData[i] + values;
          }
      }
  }

  return returnData;
};

and then use it like:

var keys = ["foo","bar"];
var values = [".val.name", ".val.date"];
processData(data, keys, values);

But this does not work and in console I see foo="[object Object].val.name" rather than the expected foo="ACME Industries".

Community
  • 1
  • 1
Lothar
  • 3,409
  • 8
  • 43
  • 58
  • Can you post an example of the object you're working with? I would also be careful about naming the object and the parameter the same, it just looks confusing at may lead to problems. – elclanrs Aug 31 '12 at 07:18
  • ^^Agree. This `mydata[i] + bar[j]` is concatenating whatever those values are. – elclanrs Aug 31 '12 at 07:21
  • I've updated my answer to use the queries you have at the end of your question, and a demo of it working. – Lucas Green Aug 31 '12 at 07:57

3 Answers3

1

If you try:

new Object() + '.john.doe'

It will concatenate as a string, so you’ll get "[object Object].john.doe".

You should create a function that can handle dynamic property names instead (and there are plenty of those). You also might want to loose the ".foo.bar" syntax as a string (unless you plan to use eval()) and work solely with arrays instead.

David Hellsing
  • 106,495
  • 44
  • 176
  • 212
1

If you want to stick to your pattern of constructing the subscript as a string with dots in it you have to roll your own lookup function, like so:

function descend(object, sub) {
    var handle = object,
        stack = sub.split('.'),
        history = [],
        peek;

    while (handle[stack[0]]) {
        if (peek) {
            history.push(peek);
        }
        peek = stack.shift();
        handle = handle[peek];
    }

    if (stack.length > 0) {
        history.push(peek);
        throw "Traversal error, could not descend to '" + stack.join('.') + "' from '" + history.join('.') + "'.";
    }

    return handle;
}

var x = {
    a: {
        b: {
            c: 15
        },
        d: 4
    }
};

console.log(descend(x, "a"));
console.log(descend(x, "a.b"));
console.log(descend(x, "a.b.c"));
console.log(descend(x, "a.d"));

function processData(data, keys, values) {
    if (keys.length !== values.length) {
        throw "Mismatched keys and value lookups";
    }

    var i,
        len = keys.length,
        gathered = {},
        k,
        scratch,
        v;

    for (i = 0; i < len; i += 1) {
        k = descend(data, keys[i]);
        scratch = values[i].split('.');
        scratch.shift();
        v = descend(k, scratch.join('.'));
        gathered[keys[i]] = v;
    }

    return gathered;
}

var data = {
    foo: {
        val: {
            name: "ACME Industries"
        }
    },
    bar: {
        val: {
            date: (new Date())
        }
    }
};
var keys = ["foo","bar"];
var values = [".val.name", ".val.date"];
processData(data, keys, values);

Please note: this will not be nearly as performant as coding without this style of lookup.

Lucas Green
  • 3,951
  • 22
  • 27
0

If I understand correctly you need to use

mydata[i]["val"]["name"]

So, I'd use something like this:

var result =getItemByValuesPath(myData[i],values);
alert(result);

function getItemByValuesPath(item, values)
{
    var result = item;

    var vals = values.split(".");
    for(var j=0; j<values.length; j++)
    {
        if(result==undefined)
            {
                    return null;
            }
    result = result[values[j]];
    }
}
Mikhail Payson
  • 923
  • 8
  • 12