简体   繁体   English

将字符串数组转换为嵌套 Object

[英]Convert array of string to nested Object

I have an array of string, I want to convert to nested object where key is value of array.我有一个字符串数组,我想转换为嵌套的 object,其中键是数组的值。 I've try with reduce, but all of the value nested with the last object is last item from the array.我尝试使用 reduce,但嵌套在最后一个 object 中的所有值都是数组中的最后一项。 Can you help me?你能帮助我吗? Thanks!谢谢!

let m = [
  '1.',
  '1.1.',
  '1.2.',
  '1.3.',
  '1.4.',
  '1.1.1.',
  '1.1.2.',
  '1.1.3.',
  '1.2.1.',
  '1.2.2.',
  '1.3.1.',
  '1.3.2.',
  '1.3.3.',
  '1.3.4.',
  '1.4.1.',
  '1.4.3.',
];

I want to convert this array to nested object.我想将此数组转换为嵌套的 object。

Return返回

  {
    "1":{
        "1":{
            "1":"1.1.1.", 
            "2":"1.1.2.", 
            "3":"1.1.3."
        }, 
        "2":{
            "1":"1.2.1.", 
            "2":"1.2.2."
        }, 
        "3":{
            "1":"1.3.1.", 
            "2":"1.3.2.", 
            "4":"1.3.4."
        }, 
        "4":{
            "1":"1.4.1.", 
            "3":"1.4.3."
        }
     }
    }

Here's a working example using reduce().这是一个使用 reduce() 的工作示例。

 let m = [ '1.', '1.1.', '1.2.', '1.3.', '1.4.', '1.1.1.', '1.1.2.', '1.1.3.', '1.2.1.', '1.2.2.', '1.3.1.', '1.3.2.', '1.3.3.', '1.3.4.', '1.4.1.', '1.4.3.', ]; const addToObj = (obj_, path, newData) => { const obj = typeof obj_ === 'string'? {}: obj_ // Special logic to cause a value at 1.2.3. to override a value at 1.2. if (path.length === 0) return newData const [head, ...tail] = path return {...obj, [head]: addToObj(obj[head] || {}, tail, newData), } } const res = m.reduce( (obj, path) => addToObj(obj, path.split('.').slice(0, -1), path), {} ) console.log(res)

It works by using a addToObj function, that'll take an object as a parameter, a path into that object, and a new value wanted at the end of that path, and it'll return a new object with the new value added.它通过使用 addToObj function 来工作,它将 object 作为参数,进入该 object 的路径,以及该路径末尾需要的新值,它会返回一个新的 object 以及添加的新值。

Special logic was added to addToObj() to make sure keys like 1.2.3. addToObj() 中添加了特殊逻辑,以确保像1.2.3. always overwrote a string value that might have been placed at 1.2.总是覆盖可能已放置在1.2. . .

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

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