Home > other >  Array of object value printing in javascript
Array of object value printing in javascript

Time:10-21

I want to print expected output values in two loop using map, Can you please help me.

var data=[{'2021':['Q2 2021','Q3 2021','Q4 2021']},
     {'2022':['Q1 2022','Q2 2022']}
    ]
   
   data.map((obj,ind)=>{
    console.log(Object.keys(obj));
    Object.keys(obj).map((yearQuarter, i) => {
                  console.log(obj[yearQuarter]);
                  })
   })
   //getting output
   //['2022']
   //['Q1 2022', 'Q2 2022']
   //Expected Output
   //'2022'
   //'Q1 2022`
   //'Q2 2022`
   

CodePudding user response:

We can use replace to make obj[yearQuarter] print by multiple lines

var data=[{'2021':['Q2 2021','Q3 2021','Q4 2021']},
     {'2022':['Q1 2022','Q2 2022']}
    ]

data.map((obj,ind)=>{
  console.log(Object.keys(obj)[0]);
  Object.keys(obj).forEach((yearQuarter, i) => {
      console.log(obj[yearQuarter].toString().replace('[]','').replaceAll(',','\n'))
   })
})

CodePudding user response:

As per my understanding, You want to print both key as well as the values (In a string format). If Yes, You are iterating the input object in a right way. Just to print the values, you can use template literals.

Live Demo :

var data = [
  {'2021':['Q2 2021','Q3 2021','Q4 2021']},
  {'2022':['Q1 2022','Q2 2022']}
];

data.map((obj,ind)=>{
  Object.keys(obj).map((yearQuarter, i) => {
    console.log(`${yearQuarter} : ${obj[yearQuarter].join(', ')}`);
  })
})

CodePudding user response:

Another approach is to make a complete line with newline characters and print it all at once

const data = [{'2021':['Q2 2021','Q3 2021','Q4 2021']},{'2022':['Q1 2022','Q2 2022']}];

const renderYear = (obj) => Object.entries(obj)
  .map(([year, quarters]) => `${year}\n${quarters.join("\n")}`);
  
const renderYears = (arr) => arr.flatMap(renderYear).join("\n")

console.log(renderYears(data));
.as-console-wrapper { max-height: 100% !important; top: 0 }

  • Related