Xy77
Xy77

Reputation: 41

How to make json from array based on values in common

Hello I have a little problem I have arrays like this:

const arrays = {
    1: [c, u, g],
    2: [c, u],
    3: [c, u ,f],
    4: [c, g],
    5: [m, c, g],
    6: [u, m]
}

Values in each array are unique. I would like to convert it to an object like this:

const object = {
  c: {
    u: {
      g: {
        ends: 1
      },
      f: {
        ends: 3
      }
      ends: 2
    },
    g: {
      m: {
        ends: 5
      }
      ends: 4
    }
  },
  u: {
    m: {
      ends: 6
    }
  }
}

Is it possible ? And if so could you give me hint, piece of code or any other type of answer I'm hard stuck here.

Upvotes: 2

Views: 62

Answers (1)

adiga
adiga

Reputation: 35222

You can loop through the entries of the object. Then reduce each value array and create nested object in each iteration. The reduce returns the final nested object. So, add an ends property here.

If you don't want sorted nested path, you can skip the sort bit

const input = {
  1: ["c", "u", "g"],
  2: ["c", "u"],
  3: ["c", "u", "f"],
  4: ["c", "g"],
  5: ["m", "c", "g"],
  6: ["u", "m"]
}

const output = {};

for (const [n, paths] of Object.entries(input)) {
  paths
    .sort()
    .reduce((acc, path) => (acc[path] = acc[path] || {}), output)
    .ends = +n
}

console.log(output)

Upvotes: 1

Related Questions