0
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 a tree like this, which is more complex, deeper and bigger. The properties are always on the last level.

What I am trying to do is get all the properties with their values and push them in a new array. Basically I am trying to get an array like 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 where to start. Any ideas?

Alexandru
  • 21
  • 1
  • 6
  • 2
    Shouldn't be it `x1_x4`? – kind user Apr 05 '17 at 20:53
  • 1
    Your desired output is not valid JavaScript. – trincot Apr 05 '17 at 20:56
  • 1
    @trincot, the dupe target is ugly and does not help. – Nina Scholz Apr 05 '17 at 21:05
  • @Alexandru: Create a function that receives an object `o` and a string `s`. On the first call, pass `o` the main object and `s` an empty string. In the function create a result like `var res = {}`. Then iterate `o` using a `for (var k in o) {...}` loop. In the loop, check `if (typeof o[k] === "object")`, and if so make a recursive call to your function with the `o[k]` object and with `s + k + "_"`, and take its result and do `Object.assign(res, nestedRes)`. If it wasn't an object, then simply assign `o[k]` to `s + k` on the `res` object. After the loop, `return res`. –  Apr 05 '17 at 21:20
  • @NinaScholz, but the referenced question is about the same thing ("flattening" an object), which is what matters, no? If anyone has a better, cleaner answer, then why not post it there? – trincot Apr 05 '17 at 21:28

1 Answers1

1

Basically you need to flatten object? if so, here is the 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));
ajai Jothi
  • 2,284
  • 1
  • 8
  • 16