Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create an array of object from other object, but with conditional properties

I have this object:

data = {
"teste1" : "value1",
"teste2" : "value2",
"teste3" : "value3",
"noquizz": {
          "teste4": "value4",
          "teste5": "value6"
          }
}

I’m trying to get this result

 mapped = [
    {id: "teste1" : value: "value1"},
    {id: "teste2" : value: "value2"},
    {id: "teste3" : value: "value3"},
    {id: "noquizz" : answers: {
                               "teste4": "value4",
                               "teste5": "value6"
                              },
    ]

So I did

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const mapped = Object.keys(this.data).map(key => ({id: key, value: this.data[key]}));

But I must have the property "answers" when I get a key that includes the word "QUIZZ"

>Solution :

Use a ternary to check if the id includes quizz:

const data={"teste1":"value1","teste2":"value2","teste3":"value3","noquizz":{"teste4":"value4","teste5":"value6"}};

const mapped = Object.entries(data)
  .map(([id, value]) => id.includes("quizz") ? { id, answers: value } : { id, value });
  
console.log(mapped);

You can also use id.toLowerCase() first if you want case insensitive matching.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading