[英]Node.js return object keys based on its value
在nodejs 8.10中,我希望函數根據參數返回不同的對象。 是否有任何簡單的方法可以根據密鑰的值包含或不包含密鑰?
例
// I do not like this solution, there is a 2 line body
// `c` may be undefined or a string (for example)
const f = (a, b, c) => {
if (c) return ({ a, b, c });
else return { a, b }
}
我們可以根據其值對c
進行簡單的返回嗎? 我期望這樣的事情:
// I expect this kind of solution.
const f = (a, b, c) => ({ a, b, ___????___ })
您無法執行此操作,但是可以:
const f = (a, b, c) => (c ? { a, b, c } : { a, b });
要么
const f = (a, b, c) => {
const result = { a, b };
if (c) result.c = c;
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.