Javascript 对象分解

Javascript 对象分解,javascript,node.js,ecmascript-6,lodash,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 = {}

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

您可以使用三元运算符来测试条件,一次定义
doc
。如果需要删除
未定义的
属性,则您可以在之后通过
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
(提高代码可读性)。

元素
中的实际内容是什么?第一行是分解对象,然后你所做的就是“将其重新组合”。通过“删除”不必要的项,可能有一些方法可以“破坏”结构,但这“可能”应该从了解“源”实际上是什么的角度来进行。如果您描述source.element实际上是json响应,那么这是一个更好的问题,我只需要指定的属性,但整个代码都进入了Messas,您被要求在这里实际显示一个数据示例。重点是,最好是“排除”字段,而不是显式地“包含”。只显示一个示例。@CertainPerformance我不确定这一点,因为我认为对map、filter、reduce或lodash方法缺乏了解。这就是我在这里发帖的原因,我认为错了吗?@BatuG.-您尚未根据:destructure object for my needs确定您的需求-请确定您的需求,并提供输入和预期输出。
MongoClient.connect(url,{ignoreUndefined:true})
在这里可能会有所帮助。