Javascript - nested dictionary from array of strin

2020-01-20 10:38发布

I have to translate an array to nested dictionary.

In case i have a string array. each string combined from numbers that seprated by dots, and each number means a key in the translated dictionary. (except the last number)

e.g.

i have this array: array = ["5.1.1.1","5.1.1.2","5.1.1.3",..."5.2.1.2","5.2.1.4"..."1.1.1.1"..."1.2.1.3"]

and i need output to be this:

var output = {
    '5': {
        '1': {
            '1': [1,2,3],
            '2': [1]
        },
        '2':{
            '1': [2,4],
            '2': [1]
        }
    },
    '1': {
        '1':{
            '1':[1,2,5],
            '2':[1]
        },
        '2':{
            '1':[2,3]
        }
    }
};

i have an opposite function, which get a nested dictionary and her output is an array.

link: https://stackoverflow.com/a/59191937/7593555

Thanks for helping :).

1条回答
霸刀☆藐视天下
2楼-- · 2020-01-20 11:17

You can use a recursive function, using the output from your last question:

const arr = [
  "1.1.1.1",
  "1.1.1.2",
  "1.1.1.5",
  "1.1.2.1",
  "1.2.1.2",
  "1.2.1.3",
  "5.1.1.1",
  "5.1.1.2",
  "5.1.1.3",
  "5.1.2.1",
  "5.2.1.2",
  "5.2.1.4",
  "5.2.2.1"
]

const map = {}
const addProp = ([k, ...r], map) => {
  if (r.length === 1) return map[k] ? map[k].push(r[0]) : map[k] = r
  if (map[k]) {
    addProp(r, map[k])
  } else {
    map[k] = {}
    addProp(r, map[k])
  }
}

arr.map(e => e.split('.')).forEach(e => addProp(e, map))

console.log(map)

查看更多
登录 后发表回答