1

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! :)

2
  • 1
    What's the 1:2:3: and 4:5:6 and 7:8:9? That's not valid Javascript syntax. Commented May 22, 2020 at 21:42
  • Sorry, edited my question! Commented May 22, 2020 at 21:57

1 Answer 1

3

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.