I have this forEach function that loops over a const object, but I want to do an if else in one line but I'm not sure how. This is how I'm doing it now.
const object = {
(Name ? (Name: _.get(object, 'abc'))), : (OtherName ? (OtherName: _.get(object, 'abc'))),
}
I'm not sure why you want this, but you can use square brackets with a ternary operator to dynamically select the key:
const _ = { get: (o,t) => "answer" } // mock lodash const Name = null // makes it choose OtherName (non-null for Name) let object = null object = { [Name? "Name": "OtherName"]: _.get(object, 'abc') } console.log(object) // or maybe this? const OtherName = "something" object = { Name: Name? _.get(object, 'abc'): OtherName } console.log(object)
I think this may be what you want:
cons object = {
[ Name || OtherName ]: _.get(object, 'abc')
};
If Name
is not falsey it will be used as the property name, otherwise OtherName
will be used.
Putting []
around the key of a property literal calculates the property name dynamically from the enclosed expression.
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.