【问题标题】:Object Destructuring对象解构
【发布时间】:2023-03-21 21:32:01
【问题描述】:

如何以更优雅的方式编写此代码。我查看了 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)
    }

【问题讨论】:

  • element 中的实际内容是什么?第一行是分解对象,然后您所做的就是“将其重新组合在一起”。可能有一些方法可以通过“删除”不必要的项目来“解构”,但是这个“可能”应该从查看“来源”实际上是什么的角度来完成。如果您描述来源,这是一个更好的问题。
  • 元素实际上是 json 响应,我只需要我指定的属性,但整个代码陷入混乱
  • 您被要求在此处实际显示数据样本。重点是“排除”字段可能比明确“包含”更好。只显示一个示例。
  • @CertainPerformance 我对此不确定,因为我认为缺乏关于 map、filter、reduce 或 lodash 方法的知识。这就是我在这里发帖的原因,我想错了吗?
  • @BatuG。 - 您尚未确定您的需求:为我的需求解构对象 - 请确定您的需求并提供输入和预期输出。

标签: javascript node.js ecmascript-6 lodash


【解决方案1】:

您可以使用三元运算符一次定义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(提高代码可读性)。

【讨论】:

  • MongoClient.connect(url, {ignoreUndefined:true}) 在这里可能会有所帮助。
猜你喜欢
  • 2019-10-28
  • 2020-06-14
  • 1970-01-01
  • 1970-01-01
  • 2021-06-23
  • 2021-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多