title: Changing attributes in an array of objects
body: <p>I have an array of objects (of arbitrary depth) with identical attributes:</p>
  
  <pre><code>var array = [],
      i;
  
  for(i = 0; i &lt; 4; i++) {
      array.push({
          'a': '0',
          'b': {
              'c': '0'
          }
      });
  }
  </code></pre>
  
  <p>I would like a function to set an attribute to a specific value in all objects like this:</p>
  
  <pre><code>// only to demonstrate, doesn't actually work!
  function set(array, attribute, value) {
      array.forEach(function(obj) {
          obj[attribute] = value;
      });
  }
  </code></pre>
  
  <p>To be able to use it like this (or similar):</p>
  
  <pre><code>set(array, 'a', 1);
  set(array, 'b.c', 5);
  </code></pre>
  
  <p>If you're having trouble understanding my question please help me clarify. Thank you in advance!</p>
  
  <h1>Solution</h1>
  
  <p>I solved it but couldn't post an answer so here it is:</p>
  
  <pre><code>function set(array, attribute, value) {
      // a.b.c =&gt; [a, b, c]
      attribute = attribute.split('.');
  
      array.forEach(function(obj) {
          // obj = array[index]
          for (i = 0; i &lt; 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;
      });
  }
  </code></pre>