简体   繁体   中英

checking inline value is exists, set to object property in declaring object _ JavaScript

suppose we want to create a new object.

let myObject = {};

and we have some property that exists in another object like:

let b = { foo: "bar"};

is it possible to check if b?.foo append foo to myObject inline in the declaration of the object?

something like this:

let myObject = { b?.foo }

I think the best you can do is:

let myObject = {
  some: "prop",
  ...(b?.foo && {foo:b.foo})
}

Or if you want to pass all the object

let myObject = {
  some: "prop",
  ...(b?.foo && b)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM