从原始对象数组创建具有特定类型和键的对象数组

时间:2018-10-12 08:19:52

标签: arrays object key destructuring

我有一个数组ob对象

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"}
      }
  ];

我想映射对象数组,并为每个事件添加一个键“类型”,以标识它是“ createdEmail ||”事件的类型。 createdLetter`

我尝试了一些操作,例如从lodash拾取,但是没有得到想要的结果。

我该如何实现?

1 个答案:

答案 0 :(得分:1)

让我们尝试第一次迭代-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
  })
)

让我们尝试一些OOP方法

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