对象解构

时间:2018-05-14 00:53:06

标签: javascript node.js ecmascript-6 lodash

如何以更优雅的方式编写此代码。我看过lodash等,但实际上找不到根据我的需要去构造对象的最佳方法。 因为我会在mongo上写这些属性,我也试图验证它们是否存在。

 const { _id, name, bio, birth_date, photos, instagram, gender, jobs, schools } = element
    let myPhotos = photos.map((photo) => photo.id)
    let insta = {}
    if (instagram) {
        insta.mediaCount = instagram.media_count
        insta.profilePicture = instagram.profile_picture
        insta.username = instagram.username
        insta.photos = instagram.photos.map((photo) => photo.image)
    }

    const doc = {}

    doc._id = ObjectId(_id)
    doc.name = name
    doc.birthDate = new Date(birth_date)

    if (bio.length) {
        doc.bio = bio
    }
    if (myPhotos.length) {
        doc.photos = myPhotos
    }
    if (Object.keys(insta).length) {
        doc.instagram = insta
    }
    doc.gender = gender

    if (jobs.length) {
        doc.jobs = jobs
    }

    if (schools.length) {
        doc.schools = schools
    }

    try {
        await collection.insertOne(doc)
    } catch (error) {
        console.log("err", error)
    }

1 个答案:

答案 0 :(得分:3)

您可以使用三元运算符一次定义doc全部来测试条件。如果需要删除undefined属性,则可以在之后通过reduce删除它们。

const { _id, name, bio, birth_date, photos, instagram, gender, jobs, schools } = element
const myPhotos = photos.map(({ id }) => id)
const insta = !instagram ? undefined : (() => {
  const { media_count, profile_picture, username, photos } = instagram;
  return {
    mediaCount: media_count,
    profilePicture: profile_picture,
    username,
    photos: photos.map(({ image }) => image)
  }
})();
const docWithUndef = {
  _id: ObjectId(_id),
  name,
  gender,
  birthDate: new Date(birth_date),
  bio: bio.length ? bio : undefined,
  photos: myPhotos.length ? myPhotos : undefined,
  instagram: insta,
  jobs: jobs.length ? jobs : undefined,
  schools: schools.length ? schools : undefined,
}
const doc = Object.entries(docWithUndef)
.reduce((accum, [key, val]) => {
  if (val !== undefined) accum[key] = val;
  return accum;
});
try {
  await collection.insertOne(doc)
} catch (error) {
  console.log("err", error)
}

注意参数的解构以减少语法噪音,并使用const而不是let(提高代码可读性)。