如何以更优雅的方式编写此代码。我看过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)
}
答案 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
(提高代码可读性)。