将三个数组转换为嵌套对象

时间:2017-09-27 07:55:25

标签: javascript arrays object ecmascript-6 lodash

我想创建一个嵌套对象,就像这样

var obj; 
obj = [
    {
        "a": {
            "A" : "aA",
            "B" : "aB",
            "C" : "aC"
        }

    },
    {
        "b": {
            "A" : "bA",
            "B" : "bB",
            "C" : "bC"
        }

    },
    {
        "c": {
            "A" : "cA",
            "B" : "cB",
            "C" : "cC"
        }

    },      
]

来自这样的三个阵列

var arr1 = ["a","b","c"]
var arr2 = ["A","B","C"]
var arr3 = [["aA","aB","aC"],["bA","bB","bC"], ["cA","cB","cC"]]

使用lodash或es6有一种简单的方法吗?我实际上是使用其他函数从arr3arr1生成arr2。但这在这里并没有多大意义,但如果我要创建这样的多个数据数组并且我想通过组合数组来生成类似JSON的对象,那么什么是方便的方法?是否有关于从多个阵列创建多级嵌套对象的文档,可能超过3个阵列?

我的努力......

arr1.forEach((item)=>{
    arr2.forEach((prop)=>{
        obj[item] = {}
        obj[item][prop] =  prop
    })
})

1 个答案:

答案 0 :(得分:0)

试试这个:

  var arr1 = ["a","b","c"];
  var arr2 = ["A","B","C"];
  var arr3 = [["aA","aB","aC"],["bA","bB","bC"], ["cA","cB","cC"]];
  var obj=[]; //initializing empty obj array
  for (i=0;i<arr1.length;i++){ // loop for creating outer objects
  var insideObj = {}, sampleObj={};
  for (j=0;j<arr2.length;j++) // loop for creating inner objects
    insideObj[arr2[j]]=arr3[i][j]; // creating inner objects like {"A":"cA","B":"cB","C":"cC"}
  sampleObj[arr1[i]]= insideObj; // assigning inner object as value of outer object
  obj.push(sampleObj); // pushing outer object to my obj array
}