1

How to parse the data of Nested JS Array to Objects? I've tried different approaches by using for loop and Dict datatype but it's not working.

Background : I'm using chart.js library to show some data points in Radar Chart.Now i am trying to parse the nested arrays data and convert each array of module into single object and then pass it's data to visualization chart.

// Input--> 
JavaScript_Array=
[["Q1","Module1",9],["Q2","Module1",5],["Q3","Module1",8],
["Q1","Module2",5],["Q2","Module2",9],["Q3","Module2",1],
["Q1","Module3",2],["Q2","Module3",1],["Q3","Module3",3],
["Q1","Module4",3],["Q2","Module4",4],["Q3","Module4",2]]

//Expected Output

    Final_Array=[{label: "Module1",  data: [9,5,8],Questions:[Q1,Q2,Q3] },
                 {label: "Module2",  data: [5,9,1],Questions:[Q1,Q2,Q3]},
                 {label: "Module3",  data: [2,1,3],Questions:[Q1,Q2,Q3]},
                 {label: "Module4",  data: [3,4,2],Questions:[Q1,Q2,Q3]}]

1 Answer 1

2

You could reduce the array and group based on the label. Create an accumulator with each unique label as the key and the object you need in the output as value. If the label doesn't exist on the accumulator yet, add it. Then, update the respective keys of the object. Use Object.values() get the array of values from the grouped object:

const input=[["Q1","Module1",9],["Q2","Module1",5],["Q3","Module1",8],["Q1","Module2",5],["Q2","Module2",9],["Q3","Module2",1],["Q1","Module3",2],["Q2","Module3",1],["Q3","Module3",3],["Q1","Module4",3],["Q2","Module4",4],["Q3","Module4",2]];

const merged = input.reduce((acc, [q, label, n]) => {
  acc[label] = acc[label] || { label, data: [], Questions: [] };
  acc[label].data.push(n);
  acc[label].Questions.push(q);
  return acc
}, {})

const output = Object.values(merged)

console.log(output)

This is how the merged/ accumulator object looks like

{
  "Module1": {
    label: "Module1",
    data: [9, 5, 8],
    Questions: ["Q1", "Q2", "Q3"]
  },
  "Module2": {
    ...
  }, 
  "Module3": {
    ...
  }
}
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.