将数组转换为嵌套对象

时间:2015-02-02 12:57:23

标签: javascript arrays 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"
    }
}

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

3 个答案:

答案 0 :(得分:3)

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

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;

的数据中的所有内容

答案 1 :(得分:0)

这是使用Ramda.js的解决方案

2
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))

答案 2 :(得分:-1)

我没有得到你想要的解决方案,因为有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()将在数组中的每个项目上调用提供的函数。