将数组转换为嵌套对象

Transformation array to nested object

我尝试将一些数据转换为 javascript 对象。数据如下所示:

data = [["a","a","a","value1"],
["a","a","b","value2"],
["a","b","value3"],
["a","c","a","value4"]]

我想得到的是:

a = {
    "a":{
        "a":"value1",
        "b":"value2"
        },
    "b":"value3",
    "c":{
        "a":"value4"
    }
}

由于嵌套属性的数量各不相同,我不知道如何进行此转换。

我没有得到你想要的解决方案,因为有 4 个数据块,但最终对象中只有 3 个属性。

但是,您可以通过以下方式遍历数组及其子数组:

var data = [["a","a","a","value1"],
["a","a","b","value2"],
["a","b","value3"],
["a","c","a","value4"]];

//Store your results in here
var result = {};

//Iterate each block of data in the initial array
data.forEach(function(block){

    //block will refer to an array

    //repeat with the child array
    block.forEach(function(item){
        //item will point to an actual item in the child array
    });

});

forEach() 将对数组中的每个项目调用提供的函数。

这应该是您正在寻找的功能:

function addItemToObject(dict, path){
  if (path.length == 2){
    dict[path[0]] = path[1];
  } else {
    key = path.shift()
    if (! dict[key]) {
      dict[key] = {};
    }
    addItemToObject(dict[key], path);
  }
  return dict;
}

var result = data.reduce(addItemToObject,{});

函数addItemToObject是一个创建深度并插入值的递归函数。

这适用于使用 reduce 的所有数据;

这是一个使用 Ramda.js

的解决方案

const data = [
  ["a","a","a","value1"],
  ["a","a","b","value2"],
  ["a","b","value3"],
  ["a","c","a","value4"]
]

const transformData =
  R.pipe(
    R.map(R.juxt([R.init, R.last])),
    R.reduce(
      (obj, [path, value]) =>
        R.assocPath(path, value, obj),
      {},
    ),
  )

console.log(transformData(data))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>