Skip to content
Advertisement

How to convert array into JavaScript object

I have an array like this (which is similar to a JSON array) of length n:

const mainData = [
  {
    phrase: "Phrase 1",
    categorynumber: 1,
    optionnumber: 1,
  },
  {
    phrase: "Phrase 2",
    categorynumber: 1,
    optionnumber: 2,
  },
  {
    phrase: "Phrase 3",
    categorynumber: 2,
    optionnumber: 1,
  },
  {
    phrase: "Phrase 4",
    categorynumber: 3,
    optionnumber: 1,
  },
  {
    phrase: "Phrase 5",
    categorynumber: 3,
    optionnumber: 1,
  },
  {
    phrase: "Phrase 6",
    categorynumber: 3,
    optionnumber: 2,
  },
];

I would like to convert it into a nested Object like so:

jsObject = {
  1: {
    1: ["Phrase 1"],
    2: ["Phrase 2"],
  },
  2: {
    1: ["Phrase 3"],
  },
  3: {
    1: ["Phrase 4", "Phrase 5"],
    2: ["Phrase 6"],
  },
};

Essentially, the object is categorised according to the categorynumber and then optionnumber. (Please keep the format of “Phrase 4” and “Phrase 5” in view.)

Advertisement

Answer

Reduce the dataset by accessing the categorynumber as the main key, and the optionnumber as the subkey. You can apply new options to the existing category by spreading (...) the new option and wrapping it within an array.

If you are appending additional phrases, you will need to also grab the existing array and spread the new value.

const mainData = [
  { phrase: "Phrase 1", categorynumber: 1, optionnumber: 1, },
  { phrase: "Phrase 2", categorynumber: 1, optionnumber: 2, },
  { phrase: "Phrase 3", categorynumber: 2, optionnumber: 1, },
  { phrase: "Phrase 4", categorynumber: 3, optionnumber: 1, },
  { phrase: "Phrase 5", categorynumber: 3, optionnumber: 1, },
  { phrase: "Phrase 6", categorynumber: 3, optionnumber: 2, },
];

const jsObject = mainData.reduce((acc, { phrase, categorynumber, optionnumber }) => ({
  ...acc,
  [categorynumber]: {
    ...(acc[categorynumber] ?? {}),
    [optionnumber]: [...(acc[categorynumber]?.[optionnumber] ?? []), phrase]
  }
}), {});

console.log(jsObject);
.as-console-wrapper { top: 0; max-height: 100% !important; }
<!--

jsObject = {
  1: {
    1: ["Phrase 1"],
    2: ["Phrase 2"]
  },
  2: {
    1: ["Phrase 3"]
  },
  3: {
    1: ["Phrase 4", "Phrase 5"],
    2: ["Phrase 6"]
  }
}

-->
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement