0

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`
   

3 Answers 3

1

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'))
   })
})

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

9 Comments

This is not working in react
@SupriyaKumari What's the prolem,it has nothing to do with react,you might need to change \n to <br/>
Still not working, is there any other way?
@SupriyaKumari need to know more details about your code,maybe we need a chat
|
0

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(', ')}`);
  })
})

Comments

0

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 }

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.