Format output of an array map Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Format output of an array map without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am trying to make a function that counts duplicates, this works but not in the output format I need. This is my function:

    var duplicateCount = {};
    countryArray.forEach(e => duplicateCount[e] = duplicateCount[e] ? duplicateCount[e] + 1 : 
    1);
     result5 = Object.keys(duplicateCount).map(e => {return {key:e, count:duplicateCount[e]}});
    console.log("result5", result5);

The output I get is:

    result5 
    (3) [{…}, {…}, {…}]
    0: {e: "CRM", count: 6}
    1: {e: "TSA", count: 8}
    2: {e: "PCS", count: 3}
    length: 3
    __proto__: Array(0)

The output I need is:

    result5 
    (3) [{…}, {…}, {…}]
    0: {"CRM", 6}
    1: {"TSA", 8}
    2: {"PCS", 3}
    length: 3
    __proto__: Array(0)

Any help is good. Thank!!

Answer

Did you mean you want the e property to be the key? (it shows a , instead of 🙂

const data = [
   {e: "CRM", count: 6},
   {e: "TSA", count: 8},
   {e: "PCS", count: 3}
  ]
     

const output1 = data.map(obj => ({[obj.e]:null, [obj.count]:null}))

const output2 = data.map(obj => ({[obj.e]:obj.e, [obj.count]:obj.count}))

const output3 = data.map(obj => ([obj.e, obj.count]))



console.log("output1:",output1, "output2:",output2, "output3:",output3)
We are here to answer your question about Format output of an array map - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji