Javascript - nested dictionary from array of strin

2020-01-20 10:39发布

问题:

Closed. This question needs to be more focused. It is not currently accepting answers.

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed last month.

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:

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)