根据属性从对象数组创建对象

时间:2017-11-07 16:28:26

标签: javascript arrays object-properties

这是一个糟糕的标题,但我想要做的一个例子如下。

我有以下对象数组(本例中为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",
  }
]

任何帮助都会很棒!

1 个答案:

答案 0 :(得分: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; }