首页 \ 问答 \ 对象解构(Object Destructuring)

对象解构(Object Destructuring)

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

How can I write this code in more elegant way. I have looked on lodash etc. but couldn't actually find the best way to destructure object for my needs. Because I will write those properties on mongo I also tried to verify if they are exist or not.

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

原文:https://stackoverflow.com/questions/50321925
更新时间:2019-12-14 01:00

最满意答案

您可以使用三元运算符一次定义doc all来测试条件。 如果需要删除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 (提高代码可读性)。


You could define the doc all at once using the ternary operator to test conditions. If the undefined properties need to be removed, then you can remove them via reduce afterward.

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

Note the destructuring of the arguments to reduce the syntax noise, and the use of const rather than let (improves code readability).

2018-05-14

相关问答

更多

对象解构:如何使用中间嵌套属性(object destructuring: how to use intermediate nested property)

我能想到的最接近的是: var { iWantThis, iWantThis: { andThis, andThisToo } } = x; 我以为我会使用let ,如果我使用的是ES6;) The closest I can come up with is: var { iWantThis, iWantThis: { andThis, andThisToo } } = x; Thought I'd use let instead, if I'm using ES6 ;)

解构一个对象而不指定它的属性(Destructuring an object without specifying its properties)

这是with(){}结构允许的: var obj = {a: 1}; with (obj) { console.log(a); } 然而,这种结构严重受挫,基本上被弃用(它在严格模式下抛出一个错误),因为它有一些主要的缺点: 你的代码难以阅读,因为无法区分1)来自外部作用域的变量2)局部变量3)来自对象的属性。 您的代码无法优化,因为JavaScript引擎无法知道您的变量来自哪里。 你的代码很难重构,因为如果你向obj引入一个属性,它可能会影响一些现有的局部变量,例如: var obj = ...

对象解构(Object Destructuring)

您可以使用三元运算符一次定义doc all来测试条件。 如果需要删除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 ...

对象解构的特殊行为(Peculiar behaviour of object destructuring)

正如我的评论所示,您可以在这里看到问题: console.log('PAYLOAD', payload); 现在,如果你检查控制台结果,你会得到这个日志: rs.store.ts:73 PAYLOAD RsRosCoughUiUpdate {payload: FormState}. 它表示payload是RsRosCoughUiUdpate ,它是一个具有称为FormState类型的payload内容属性的对象。 我假设FormState是一种符合你的IFormState接口的类型。 所以,当 ...

类成员的对象解构(object destructuring on class members)

有可能 fetchData(data) { Object.assign(this, data); } 对于未经过抽样的数据。 要么 fetchData({ id, name, ... }) { Object.assign(this, { id, name, ... }); } 用于消毒数据。 使用Lodash _.pick对于做Object.assign(this, _.pick(data, ['id', 'name', ...]))是有益的Object.ass ...

通过解构为新对象赋值(Assign value to new object via destructuring)

用分号终止let obj = {}行解决了这个问题: let parameter = {id : 10, username : 'john'}; let obj = {}; ({id : obj.iduser, username : obj.user} = parameter); console.log(obj); Terminating the let obj = {} line with a semicolon solves this: let parameter = {id : 10, ...

嵌套对象解构[重复](Nested Object destructuring [duplicate])

const { user: { name: { first: firstName = 'firstName', last: lastName = 'lastName' } = {} } = {} } = data const { user: { name: { first: firstName = 'firstName', last: lastName = 'lastName' } = {} } = {} } = data

具有解构的对象属性赋值?(Object property assignment with destructuring?)

我想你将不得不重复dst : ({a: dst.a, b: dst.b} = src); I think you’re going to have to repeat dst: ({a: dst.a, b: dst.b} = src);

为什么这个对象解构不起作用?(Why isnt this object destructuring working?)

您需要使用name和age作为从对象中解构出来的变量,如下所示: let obj={age: "3", name: "spike"}; let {age, name}=obj; console.log(age); console.log(name); 或者,您可以使用以下语法为解构结构变量指定新名称: let obj={age: "3", name: "spike"}; let {age: a, name: b}=obj; console.log(a); console.log ...

对象分配的嵌套解构(Nested Destructuring on Object Assignments)

对于嵌套级别,您可以重复相同的语法,如同对顶级进行解构: 根据您的评论编辑 我需要数组中的对象 let node = { ItemTitle: 'Title', ItemId: 5, Menu: {Item: [{ItemId: 579}]} } let { ItemId: id, // extract `node.ItemId` into a variable called `id` ItemTitle: title, // extract `n ...

相关文章

更多

最新问答

更多
  • 如何保护Solr只允许SELECT请求给用户并禁止其他任何东西?(How to secure Solr to allow SELECT request to only users and disallow anything else?)
  • XPath表达式无效/错误TFHpple SWIFT 1.2(XPath Expression not working/incorrect TFHpple SWIFT 1.2)
  • css3 3D变换不能平滑地制作动画(css3 3D transform doesn't animate smoothly)
  • 运行时错误'91'和Outlook.Application = <对象变量或没有设置块变量>?(Run-time error '91' & Outlook.Application = Object variable or With block variable not set?)
  • 慢的webservice问题(Slow webservice problem)
  • textview的不正确对齐方式(Improper alignment of a textview)
  • 在第一步“Hello World”中出现Java错误(Cannot run “Hello World” program in Eclipse)
  • 为什么十六进制地址是14个字符?(why the hex address is 14 character?)
  • 如何在Python中的不同类中使用变量?(How to use variable in different classes in Python?)
  • asp:GridView HYPERLINKFIELD - datanavigateurlformatstring中的asp代码(asp:GridView HYPERLINKFIELD - asp code inside datanavigateurlformatstring)
  • 关于adaboost算法(About adaboost algorithm)
  • 在Matlab上内置图像(Built in Images on Matlab)
  • java swing:输入键事件时焦点丢失(java swing: Focus lost on enter key event)
  • C#中的通用约束,T是相同的TSomethingElse,对吧?(Generic constraints in C#, T is the same TSomethingElse, right?)
  • 从mybatis中的光标获取数据(Fetching data from cursor in mybatis)
  • 在运行时从XML构建对象的最佳方法(Best way for building objects out of XMLs at runtime)
  • 在整个窗口中拉伸sf :: Sprite(Stretch sf::Sprite across entire window)
  • Selenium Node API Web驱动程序等待超时处理程序(Selenium Node API web driver wait timeout handler)
  • 函数使用并且是map的一部分(循环依赖?)(Function uses and is part of map (circular dependency?))
  • 是否可以在C ++ 14中使用可选模板参数创建类型元组?(Is possible to make a tuple of types with optional template parameters in C++14?)
  • PHP从窗帘后面打印/ f(PHP prints /f from behind the curtains)
  • JFrame的contentPane的LayoutManager(LayoutManager of JFrame's contentPane)
  • 用于Instagram Feed的图像滚动(Image Roll Overs for Instagram Feed)
  • 如何显示拉伸字体(双倍宽度/高度)?(How to display stretched font (double width/height)?)
  • 文件操作API在fileapi.h和stdio.h中的WP8差异?(WP8 differences between file manipulation APIs in fileapi.h and stdio.h?)
  • 保存失败后Rails没有回滚事务()(Rails not rolling back transaction after failed save())
  • jqgrid中的分页问题与数组数据(Pagination problem in jqgrid with array data)
  • 重定向时,通过其他页面上的URL调用javascript函数(Call javascript function through url on otherpage while Redirecting)
  • 如何使用InvokeCommandAction调用我的方法并传入参数?(How do I go about using InvokeCommandAction to call a method of mine and pass in parameters?)
  • Jquerymobile按钮仅显示页面的第一个外观(Jquerymobile buttons are shown only first apperance of the page)