0
$.each ( columns, function ( index, value ){
    var td = document.createElement('td');
    var text = document.createTextNode( data.attr( value ) );
    td.appendChild(text);
    tr.appendChild(td);
});

I have data.
I have value = "name"

I can't do data.name, I need to do the equivalent using the string. I tried .attr( value ) but that didn't work.

Smern
  • 18,746
  • 21
  • 72
  • 90
James
  • 5
  • 2

1 Answers1

-1

You can access to object properties in two ways.

With [dot] chaining or like an array.

If you have a problem with access to object property or your object property is variable then you use array access.

Simple example

var data = {
    aaa: {
        items: [
            { id: 1, name: "test" },
            { id: 2, name: "test2" }
        ]
    },
    bbb: {
        items: [
            { id: 1, name: "test" }
        ]
    }
};

In example below
if you want to set empty array in specific object and your decisive key is a variable then you can't use [dot] chaining because variable is not affected. Then you can use array access.

// set aaa as bbb
var aaa = 'bbb';

// WORK aaa is bbb
data[aaa]['items'] = [];

// DOES NOT WORK PROPERLY aaa is not bbb but still aaa
data.aaa.items = [];

Hope it helps

daremachine
  • 2,678
  • 2
  • 23
  • 34
  • Your example does not work. If you type it in your browser console, it will obviously throw an error: `TypeError: undefined is not a function`, because `data[0][name]` is equivalent to `data[0].aaa` and since your object does not have an `aaa` field it returns `undefined`... And trying to read a property of `undefined` throws a `TypeError`. Please check your examples before posting. @James Please check that the answer is actually correct before accepting. – Kyll May 10 '15 at 07:33
  • @Kyll thank you for your advice. I edited it. Now is it complete and what i wanted to say. – daremachine May 10 '15 at 12:48