Давайте попробуем выполнить первую итерацию - map
метод определит, есть ли у объекта только одно свойство, и назначит его новому созданному type
свойству:
const myDailyRutine = [{
createdLetter: {
date: "2018-10-12T05:44:44.553216+00:00",
user: {
username: "lady-gaga"
},
},
},
{
commentedEmail: {
date: "2018-10-12T05:44:44.553216+00:00",
user: {
username: "la-gaga",
display_name: "La Gaga"
},
},
},
{
commentedEmail: {
date: "2018-10-12T05:44:44.553216+00:00",
user: {
username: "maira-ter",
display_name: "Ma Ter"
},
},
},
]
const getValueOfFirstProperty = obj => {
const keys = Object.keys(obj)
if (keys.lenght > 1) throw new RangeError("Expected only one keys")
return keys[0]
}
console.log(
myDailyRutine.map(rutine => {
rutine.type = getValueOfFirstProperty(rutine)
return rutine
})
)
И давайте попробуем подход ООП
const myDailyRutine = [{
createdLetter: {
date: "2018-10-12T05:44:44.553216+00:00",
user: {
username: "lady-gaga"
},
},
},
{
commentedEmail: {
date: "2018-10-12T05:44:44.553216+00:00",
user: {
username: "la-gaga",
display_name: "La Gaga"
},
},
},
{
commentedEmail: {
date: "2018-10-12T05:44:44.553216+00:00",
user: {
username: "maira-ter",
display_name: "Ma Ter"
},
},
},
]
class Rutine {
constructor(type, rutine) {
this.type = type // not necessary as we have got instance of CommentedEmail or CreatedLetter
Object.keys(rutine[type]).forEach(key => this[key] = rutine[type][key])
}
}
class CommentedEmail extends Rutine {
constructor(rutine) {
super('commentedEmail', rutine)
}
}
class CreatedLetter extends Rutine {
constructor(rutine) {
super('createdLetter', rutine)
}
}
const rutine = rutine => {
switch (Object.keys(rutine)[0]) {
case 'commentedEmail':
return new CommentedEmail(rutine)
case 'createdLetter':
return new CreatedLetter(rutine)
}
}
console.log(
myDailyRutine.map(rutine)
)