简体   繁体   English

如何将 arrays 的数组转换为 Javascript 中的 object

[英]How to convert an array of arrays to an object in Javascript

I need the solution for the general case我需要一般情况的解决方案

for example例如

let data = [['a', 'b'],['c', 'd'],['e', 'f', 'g', 'h']];

I need this:我需要这个:

{
    "a": {
        "c": {
            "e": 0,
            "f": 0,
            "g": 0,
            "h": 0
        },
        "d": {
            "e": 0,
            "f": 0,
            "g": 0,
            "h": 0
        }
    },
    "b": {
        "c": {
            "e": 0,
            "f": 0,
            "g": 0,
            "h": 0
        },
        "d": {
            "e": 0,
            "f": 0,
            "g": 0,
            "h": 0
        }
    }
}

and data can be any random array of arrays... I tried a recursive approach but I get stuck with Map and.fromEntries method...并且数据可以是 arrays 的任何随机数组...我尝试了一种递归方法,但我被 Map 和.fromEntries 方法卡住了...

Simple recursion:简单递归:

  1. Base case - we only have one array inside the array.基本情况 - 我们在数组中只有一个数组。 We construct an object with default values from it.我们用它的默认值构造一个 object。
  2. Recursive step - we have more arrays.递归步骤 - 我们有更多 arrays。 We build up an object and each key comes from the first array, each value is a recursive call that uses the rest of the arrays:我们构建了一个 object,每个键来自第一个数组,每个值都是使用 arrays 的 rest 的递归调用:

 const buildObj = (data, defaultValue = 0) => { if (data.length > 1) return Object.fromEntries( data[0].map(x => [x, buildObj(data.slice(1), defaultValue)]) ) return Object.fromEntries( data[0].map(x => [x, defaultValue]) ); } console.log(buildObj([ ['e', 'f', 'g', 'h'] ])); console.log(buildObj([ ['c', 'd'], ['e', 'f', 'g', 'h'] ])); console.log(buildObj([ ['a', 'b'], ['c', 'd'], ['e', 'f', 'g', 'h'] ])); console.log(buildObj([ ['a', 'b'], ['c', 'd'], ['e', 'f', 'g', 'h'] ], 42)); //different default

Can also be represented by:也可以表示为:

  1. Base case - return the default value.基本情况 - 返回默认值。
  2. Recursive step - We build up an object and each key comes from the first array, each value is a recursive call that uses the rest of the arrays.递归步骤 - 我们构建了一个 object,每个键来自第一个数组,每个值都是使用 arrays 的 rest 的递归调用。

 const buildObj = (data, defaultValue = 0) => { if (data.length.== 0) return Object.fromEntries( data[0],map(x => [x. buildObj(data,slice(1); defaultValue)]) ); return defaultValue. } console,log(buildObj([ ['e', 'f', 'g'; 'h'] ])). console,log(buildObj([ ['c', 'd'], ['e', 'f', 'g'; 'h'] ])). console,log(buildObj([ ['a', 'b'], ['c', 'd'], ['e', 'f', 'g'; 'h'] ])). console,log(buildObj([ ['a', 'b'], ['c', 'd'], ['e', 'f', 'g', 'h'] ]; 42)); //different default

I think this runs good.我认为这运行良好。 Runs recursion with step.使用 step 运行递归。 You can change forEach to for loop, if you want.如果需要,您可以将forEach更改为for循环。


let data = [['a', 'b'],['c', 'd'],['e', 'f', 'g', 'h']];

const arrToDict = (data) => {
    const recursive  = (depth = 0) => {
    let dict = {}
    
    if (data.length === depth + 1) {
        data[depth].forEach(el => {
        dict[el] = 0
    })
    } else {
        data[depth].forEach(el => {
        dict[el] = recursive(depth+1)
        })
    }
    return dict
}
return recursive();
}

arrToDict(data)

I have used a recursion for converting each index to object and then used Memoization for a more efficient solution我使用递归将每个索引转换为 object,然后使用Memoization获得更有效的解决方案

Base Case : When the index has gone out of bounds of current array Recursive Case : recurse over the next index and assign the next objectified index as a value to the current key基本情况:当索引超出当前数组的范围时递归情况:递归下一个索引并将下一个对象化索引作为值分配给当前键

 //store the index which is already iterated/objectified //this is just for LESS COMPUTATION and MORE EFFICIENCY const memoizeObjectifiedIndex = {}; let data = [['a', 'b'],['c', 'd'],['e', 'f', 'g', 'h']]; //basic recursive approach function createObject(data,index){ //base case, //if the index is just outside the length of array, //here that index=3, since array is 0 indexed and last index is 2 if(index === data.length) return 0; //check in memoized object if current index is already objectfied if(memoizeObjectifiedIndex[index]){ //you can check the hits when this condition is true and COMPUTATION is saved // console.log("Found for index ", index); return memoizeObjectifiedIndex[index];} const obj={}; data[index].forEach((key) => { //assign the next objectified index as value to current key obj[key] = createObject(data,index+1); }) //store the object for current index for future use memoizeObjectifiedIndex[index] = obj; return obj; } console.log(createObject(data,0))

Note : You can see better output by copying and running this code in browser console.注意:通过在浏览器控制台中复制并运行此代码,您可以看到更好的 output。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM