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

Time:11-16

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

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"

CodePudding user response:

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.

  • Related