cmarin
cmarin

Reputation: 59

Pivot/Transform Javascript array of objects

I need help with this please. I have the following array of objects:

[
  {
    name: "A",
    id: "q1",
    history: {
        "1:2:3": {a: 0, b: 0, c: 0},
        "4:5:6": {a: 1, b: 1, c: 1},
        "7:8:9": {a: 2, b: 2, c: 2}
     }
  },
  {
    name: "B",
    id: "q2",
    history: {
        "1:2:3": {a: 3, b: 3, c: 3},
        "4:5:6": {a: 4, b: 4, c: 4},
        "7:8:9": {a: 5, b: 5, c: 5}
     }
  },
  {
    name: "C",
    id: "q3",
    history: {
        "1:2:3": {a: 6, b: 6, c: 6},
        "4:5:6": {a: 7, b: 7, c: 7},
        "7:8:9": {a: 8, b: 8, c: 8}
     }
  }
]

and I want to obtain the following result:

{
  "1:2:3": {
    "q1": {a: 0, b: 0, c: 0},
    "q2": {a: 3, b: 3, c: 3},
    "q3": {a: 6, b: 6, c: 6}
  },
  "4:5:6": {
    "q1": {a: 1, b: 1, c: 1},
    "q2": {a: 4, b: 4, c: 4},
    "q3": {a: 7, b: 7, c: 7}
  },
  "7:8:9": {
    "q1": {a: 2, b: 2, c: 2},
    "q2": {a: 5, b: 5, c: 5},
    "q3": {a: 8, b: 8, c: 8}
  }
}

I want the result to be an object with 1:2:3, 4:5:6, 7:8:9 the keys.

Some solutions please? Thank you! :)

Upvotes: 1

Views: 430

Answers (1)

Józef Podlecki
Józef Podlecki

Reputation: 11283

It's a good example of how can one use reduce

const data = [{
    name: "A",
    id: "q1",
    history: {
      "1:2:3": {
        a: 0,
        b: 0,
        c: 0
      },
      "4:5:6": {
        a: 1,
        b: 1,
        c: 1
      },
      "7:8:9": {
        a: 2,
        b: 2,
        c: 2
      }
    }
  },
  {
    name: "B",
    id: "q2",
    history: {
      "1:2:3": {
        a: 3,
        b: 3,
        c: 3
      },
      "4:5:6": {
        a: 4,
        b: 4,
        c: 4
      },
      "7:8:9": {
        a: 5,
        b: 5,
        c: 5
      }
    }
  },
  {
    name: "C",
    id: "q3",
    history: {
      "1:2:3": {
        a: 6,
        b: 6,
        c: 6
      },
      "4:5:6": {
        a: 7,
        b: 7,
        c: 7
      },
      "7:8:9": {
        a: 8,
        b: 8,
        c: 8
      }
    }
  }
]

const result = data.reduce((acc, item) => {

  const keys = Object.keys(item.history);

  for (let key of keys) {
    acc[key] = {
      ...(acc[key] || {}),
      [item.id]: item.history[key]
    }
  }

  return acc;
}, {})

console.log(result);

Upvotes: 3

Related Questions