1

I have a JSON that looks like this

[{
                "teacher": "teacher1",
                "student": "student1",
                "segment": "product"
            },
            {
                "teacher": "teacher1",
                "student": "student1",
                "segment": "UNR"
            },
            {
                "teacher": "teacher1",
                "student": "student1",
                "segment": "product"
            },
            {
                "teacher": "teacher2",
                "student": "student1",
                "segment": "UNR"
            },
            {
                "teacher": "teacher2",
                "student": "student2",
                "segment": "product"
            }
        ]

With the help of create complex table from the Json data i can create an array counting each teacher and its count by I want to add another detail in it now. I want to calculate the instance of the segment for each teacher as well like below

[
    {
        "teacherName": "teacher1",
        "teacherCount": "3",
        "productCount":"2",
        "unrCount":"1"
    },
    {
        "teacherName": "teacher2",
        "teacherCount": "2",
        "productCount":"1",
        "unrCount":"1"
    }
]

2 Answers 2

1

One option is using reduce to loop thru the array. Use teacher as the key to summarize the data into an object. Use Object.values to convert object into an array.

const data = [{"teacher":"teacher1","student":"student1","segment":"product"},{"teacher":"teacher1","student":"student1","segment":"UNR"},{"teacher":"teacher1","student":"student1","segment":"product"},{"teacher":"teacher2","student":"student1","segment":"UNR"},{"teacher":"teacher2","student":"student2","segment":"product"}]

const result = Object.values(data.reduce((c, {teacher,segment}) => {
  c[teacher] = c[teacher] || {"teacherName": teacher,"teacherCount": 0,"productCount": 0,"unrCount": 0};
  c[teacher].teacherCount++;

  if (segment === "product") c[teacher].productCount++;
  if (segment === "UNR") c[teacher].unrCount++;

  return c;
}, {}));

console.log(result);

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

Comments

1

let say d is your json, then this code will work.

d.reduce((s, i)=>{
    teacher=i["teacher"]
    t=(s[teacher]==null)?{teacherCount:0}:s[teacher]
    seg=i['segment']
    t[seg]=(t[seg]==null)?1:(t[seg]+1)
    t["teacherCount"]+=1
    s[teacher]=t
    return s
},{})

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.