我尝试将一些数据转换为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"
}
}
由于嵌套属性的数量不同,我不知道如何进行这种转换。
答案 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)
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()将在数组中的每个项目上调用提供的函数。