Search code examples
javascriptarraysobject-properties

Creating object from array of objects based on properties


That is a bad title but an example of what I am trying to do is below.

I have the following array of objects (3 in this example but could be any number).

objArray = 
[
  {
    name : "My_Object_1",
    values : ["bob","tom","phil"],
    children : {
        "bob":["terry","carl"],
        "tom" : ["paul","kevin"],
        "phil" : []
    }
  },
  {
    name : "My_Object_2",
    values : ["terry","carl","paul","kevin"],
    children : {
        "terry":[],
        "carl":[],
        "paul":["jo","tim"],
        "kevin":[]
    }
  },
  {
    name : "My_Object_3",
    values : ["jo","tim"],
    children:{}
  }
]

I need to create a new array of objects for each combination if there is a child in the next object in the original array like this:

finalResult = [
  {
    "My_Object_1" : "phil",
    "My_Object_2" : "",
    "My_Object_3" : "",
  },
  {
    "My_Object_1" : "bob",
    "My_Object_2" : "terry",
    "My_Object_3" : "",
  },
  {
    "My_Object_1" : "bob",
    "My_Object_2" : "carl",
    "My_Object_3" : "",
  },
  {
    "My_Object_1" : "tom",
    "My_Object_2" : "kevin",
    "My_Object_3" : "",
  },
  {
    "My_Object_1" : "tom",
    "My_Object_2" : "paul",
    "My_Object_3" : "jo",
  },
  {
    "My_Object_1" : "tom",
    "My_Object_2" : "paul",
    "My_Object_3" : "tim",
  }
]

Any help would be great!


Solution

  • You could take a recursive approach while checking the items of the next level. at the end return an array with objects.

    The order is defined by the order of the given values property.

    var array = [{ name: "My_Object_1", values: ["bob", "tom", "phil"], children: { bob: ["terry", "carl"], tom: ["paul", "kevin"], phil: [] } }, { name: "My_Object_2", values: ["terry", "carl", "paul", "kevin"], children: { terry: [], carl: [], paul: ["jo", "tim"], kevin: [] } }, { name: "My_Object_3", values: ["jo", "tim"], children: {} }],
        result = function create(array) {
            function iter(keys, path) {
                var index;
    
                path = path || [];
                index = path.length;
    
                (keys || array[index].values).forEach(function (k) {
                    var ref = array[index].children[k],
                        temp = path.concat(k),
                        object = {};
    
                    if (ref && ref.length) {
                        return iter(ref, temp);
                    }
                    [1, 2, 3].forEach(function (v, i) { object['key' + v] = temp[i] || ''; });
                    result.push(object);
                });
            };
    
            var result = [];
            iter();
            return result;
        }(array);
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }