破折号,如果还有一行的话

问题描述 投票:0回答:1

我有这个遍历const对象的forEach函数,但是我想在一行中执行if if else,但我不确定如何做。这就是我现在的做法。

const object = {
(Name ? (Name: _.get(object, 'abc'))), : (OtherName ? (OtherName: _.get(object, 'abc'))),
}
javascript lodash
1个回答
0
投票

我不确定为什么要这样做,但是可以将方括号和三元运算符一起使用来动态选择键:

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)
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.