0

I have an array of objects (of arbitrary depth) with identical attributes:

var array = [],
    i;

for(i = 0; i < 4; i++) {
    array.push({
        'a': '0',
        'b': {
            'c': '0'
        }
    });
}

I would like a function to set an attribute to a specific value in all objects like this:

// only to demonstrate, doesn't actually work!
function set(array, attribute, value) {
    array.forEach(function(obj) {
        obj[attribute] = value;
    });
}

To be able to use it like this (or similar):

set(array, 'a', 1);
set(array, 'b.c', 5);

If you're having trouble understanding my question please help me clarify. Thank you in advance!

Solution

I solved it but couldn't post an answer so here it is:

function set(array, attribute, value) {
    // a.b.c => [a, b, c]
    attribute = attribute.split('.');

    array.forEach(function(obj) {
        // obj = array[index]
        for (i = 0; i < attribute.length - 1; i++) {
            // i = 0) obj = array[index].a
            //     1) obj = array[index].a.b
            obj = obj[attribute[i]];
        }

        // array[index].a.b.c = value
        obj[attribute[i]] = value;
    });
}

1 Answers1

0
var array = [],
    i;

for(i = 0; i < 4; i++) {
    array.push({
        'a': '0',
        'b': {
            'c': '0'
        }
    });
}

set = function(array, key, value){
  for (i = 0; i < array.length; i++){
    array[i][key] = value;
  }
}

set(array, "test", "Test");
alert(array[0]['test']);

Hah, @Oriol is right, you just have a syntax error on your original funciton.

mtyson
  • 8,196
  • 16
  • 66
  • 106