javascript - Iterate through an tree and push all the properties in an array -


this question has answer here:

var obj = {     x1: {         x2: {             x3: {                 condition: false,                 condition_trust: 55.25,                 condition_2 : true,                 condition_2_trust: 56.456             }         },         x4: {             name: "aaa",             name_trust: 55.25,             name_2: "bbb",             name_2_trust: 96.42         }     } } 

i have tree this, more complex, deeper , bigger. properties on last level.

what trying properties values , push them in new array. trying array this:

array = [ x1_x2_x3_condition : false, x1_x2_x3_condition_trust : 55.25, x1_x2_x3_condition_2 : true, x1_x2_x3_condition_2_trust : 55.456, x4_name : "aaa", x4_name_trust : 55.25, x4_name_2 : "bbb", x4_name_2_trust : 96.42 ] 

i have no idea start. ideas?

basically need flatten object? if so, here solution

var obj = {    x1: {      x2: {        x3: {          condition: false,          condition_trust: 55.25,          condition_2: true,          condition_2_trust: 56.456        }      },      x4: {        name: "aaa",        name_trust: 55.25,        name_2: "bbb",        name_2_trust: 96.42      }    }  }    function flattenobject(obj) {    return object.keys(obj).reduce(function(a, k) {      if (obj[k].constructor === object) {        var o = flattenobject(obj[k]);        object.keys(o).foreach(function(key) {          a[k + '_' + key] = o[key];        });      } else {        a[k] = obj[k];      }      return a;    }, {});  }    console.log(flattenobject(obj));


Comments