0

这是一个糟糕的标题,但我正在尝试做的一个例子如下。

我有以下对象数组(在此示例中为 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:{}
  }
]

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

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

任何帮助都会很棒!

4

1 回答 1

1

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

顺序由给定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; }

于 2017-11-07T17:20:13.903 回答