根据属性从 object 的数组中创建 object

Creating object from array of objects based on properties

这个标题不好,但下面是我正在尝试做的一个例子。

我有以下 object 数组(本例中为 3,但可以是任意数字)。

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:{}
  }
]

如果原始数组中的下一个 object 中有一个 child,我需要为每个组合创建一个新的 object 数组,如下所示:

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",
  }
]

任何帮助都会很棒!

您可以在检查下一级项目时采用递归方法。最后 return 一个包含对象的数组。

顺序由给定的顺序定义 values 属性.

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; }