繁体   English   中英

使用 arrays 数组中的子项创建嵌套 object

[英]Create a nested object with children from array of arrays

我有以下 arrays 数组

let arr = [
    [ "Female" , "Male" ],
    [ "Dinner" , "Lunch" ],
    [ "No" , "Yes" ],
]

我想实现这个结构

let foo = [
    { 
        value: "Female",
        children: [
            {
                value: "Dinner",
                children: [
                    {
                        value: "No"
                    },
                    {
                        value: "Yes"
                    },
                ]
            },
            {
                value: "Lunch",
                children: [
                    {
                        value: "No"
                    },
                    {
                        value: "Yes"
                    },
                ]
             },
        ]
    },
    { 
        value: "Male",
        children: [
            {
                value: "Dinner",
                children: [
                    {
                        value: "No"
                    },
                    {
                        value: "Yes"
                    },
                ]
            },
            {
                value: "Lunch",
                children: [
                    {
                        value: "No"
                    },
                    {
                        value: "Yes"
                    },
                ]
             },
        ]
    },
]

我根本无法解决这个问题来实现这一点,因此,我没有要发布的起始代码,所以如果你能提供帮助,那就太好了。

你也可以不用递归 2 for

 let arr = [ [ "Female", "Male" ], [ "Dinner", "Lunch" ], [ "No", "Yes" ], ]; var lastChild = -1; for(var i = arr.length-1; i >= 0; i--) { var item = arr[i]; var lastChildTemp = []; for(var j = 0; j < item.length; j++) { var newChild = {value: item[j]}; if(lastChild.= -1) { newChild;children = lastChild. } lastChildTemp;push(newChild); } lastChild = lastChildTemp. } console.log(JSON,stringify(lastChildTemp,null;2));

Output:

[
  {
    "value": "Female",
    "children": [
      {
        "value": "Dinner",
        "children": [
          {
            "value": "No"
          },
          {
            "value": "Yes"
          }
        ]
      },
      {
        "value": "Lunch",
        "children": [
          {
            "value": "No"
          },
          {
            "value": "Yes"
          }
        ]
      }
    ]
  },
  {
    "value": "Male",
    "children": [
      {
        "value": "Dinner",
        "children": [
          {
            "value": "No"
          },
          {
            "value": "Yes"
          }
        ]
      },
      {
        "value": "Lunch",
        "children": [
          {
            "value": "No"
          },
          {
            "value": "Yes"
          }
        ]
      }
    ]
  }
]

这里的关键是使用backward for(从高索引开始到低索引),然后创建一个lastChild object。 然后把它放在每个下一个对象的.children属性中。

递归

递归是一种函数式遗产,因此将其与函数式风格一起使用会产生最佳结果。 这意味着避免诸如突变、变量重新分配和其他副作用之类的事情。

我们可以使用归纳归纳推理编写make(t) -

  1. 如果输入t为空,返回空结果[]
  2. (感性) t至少有一个元素。 对于第一个元素t[0]中的所有value ,返回一个新的 object {value, children}其中children是递归子问题make(t.slice(1))的结果

 const make = t => t.length == 0? [] // 1: t[0].map(value => ({ value, children: make(t.slice(1)) })) // 2 const myinput = [ [ "Female", "Male" ], [ "Dinner", "Lunch" ], [ "No", "Yes" ] ] console.log(make(myinput))

上面我们使用?:make编写为单个纯函数表达式。 这等效于命令式风格if..else -

 function make(t) { if (t.length == 0) return [] else return t[0].map(value => ({ value, children: make(t.slice(1)) })) } const myinput = [ [ "Female", "Male" ], [ "Dinner", "Lunch" ], [ "No", "Yes" ] ] console.log(make(myinput))

形象化

它有助于我们想象这些是如何工作的

make([[ "Female" , "Male" ], [ "Dinner" , "Lunch" ], [ "No" , "Yes" ]])

= [
    {value: "Female", children: make([[ "Dinner" , "Lunch" ], [ "No" , "Yes" ]]) },
    {value: "Male", children: make([[ "Dinner" , "Lunch" ], [ "No" , "Yes" ]]) }
  ]
make([[ "Dinner" , "Lunch" ], [ "No" , "Yes" ]])

= [
    {value: "Dinner", children: make([[ "No" , "Yes" ]]) },
    {value: "Lunch", children: make([[ "No" , "Yes" ]]) }
  }
make([[ "No" , "Yes" ]])

= [
    {value: "No", children: make([]) },
    {value: "Yes", children: make([]) }
  }
make([])
= []

删除空的children

现在我们了解了它是如何工作的,我们通过再添加一个条件来防止创建空的children: []属性。 t只有一个元素时,只需为元素中的所有value创建一个{value} -

 function make(t) { switch (t.length) { case 0: return [] case 1: return t[0].map(value => ({ value })) default: return t[0].map(value => ({ value, children: make(t.slice(1)) })) } } const myinput = [ [ "Female", "Male" ], [ "Dinner", "Lunch" ], [ "No", "Yes" ] ] console.log(make(myinput))

产生您正在寻找的 output -

[
  {
    "value": "Female",
    "children": [
      {
        "value": "Dinner",
        "children": [
          {
            "value": "No"
          },
          {
            "value": "Yes"
          }
        ]
      },
      {
        "value": "Lunch",
        "children": [
          {
            "value": "No"
          },
          {
            "value": "Yes"
          }
        ]
      }
    ]
  },
  {
    "value": "Male",
    "children": [
      {
        "value": "Dinner",
        "children": [
          {
            "value": "No"
          },
          {
            "value": "Yes"
          }
        ]
      },
      {
        "value": "Lunch",
        "children": [
          {
            "value": "No"
          },
          {
            "value": "Yes"
          }
        ]
      }
    ]
  }
]

你可以试试这个:

 let arr = [ ['Female', 'Male'], ['Dinner', 'Lunch'], ['No', 'Yes'] ] function makeTree(a, ch = [], currIndex = 0) { for (const item of a[currIndex]) { if (a[currIndex + 1]) { // If there is an array after this one then // include the 'children' array const obj = { value: item, children: [] } ch.push(obj) // Run the function again to fill the `children` // array with the values of the next array makeTree(a, obj.children, currIndex + 1) } else { // If this is the last array then // just include the value ch.push({ value: item }) } } return ch } const result = makeTree(arr) console.log(JSON.stringify(result, null, 2))
 .as-console-wrapper { min-height: 100% }

签出此代码段。 它根据您的需要输出。

 let arr = [ [ "Female", "Male" ], [ "Dinner", "Lunch" ], [ "No", "Yes" ], ] let foo = []; let arr2 = []; arr[2].forEach(yn => { arr2.push({ "value": yn}); }); let arr1 = []; arr[1].forEach(dl => { arr1.push({ "value": dl, "children": arr2 }); }); arr[0].forEach(fm => { foo.push({ "value": fm, "children": arr1 }); }); console.log(JSON.stringify(foo, null, 2))

使用以下代码重新排列您的数组,然后根据您的意愿进行迭代,这是动态的。 您可以在 arr 变量中有更多行。

let arr = [
 [ "Female" , "Male" ],
 [ "Dinner" , "Lunch" ],
 [ "No" , "Yes" ],
] 
let finalArray = [];
for(let i=arr.length-2; i>-1; i--){
  for(let j=0; j< arr[i].length; j++) {
    item = {}
    item[arr[i][j]] = arr[i+1];
    arr[i][j] = [];
    arr[i][j] = item;
  }
arr.pop();
}
console.log(arr);
/*output*/
[
[{
    'Female': [{
        'Dinner': ['No', 'Yes']
    }, {
        'Lunch': ['No', 'Yes']
    }]
}, {
    'Male': [{
        'Dinner': ['No', 'Yes']
    }, {
        'Lunch': ['No', 'Yes']
    }]
  }]
]

https://jsfiddle.net/Frangly/ywsL0pbt/147/

暂无
暂无

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

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