![](/img/trans.png)
[英]Turning an array of objects, into a single object with the same value for all keys?
[英]Turning a single value into an array
在我的項目中,我經常發現自己檢查一個值是否為數組。
如果該值不是數組,我會從中創建一個單元素數組。
如果值為undefined
或null
,我將創建一個空數組。
該值本身通常是對象數組或單個 object 或undefined
const array = value ? (Array.isArray(value) ? value: [value]) : [];
在我決定將其納入單獨的 util function 之前,是否有更簡潔的方法(可能使用lodash
或underscore
)?
你可以做
var eventsArray = events ? [].concat(events) : [];
.concat()
函數同時接受數組和單個參數,因此無論哪種方式最終都可以得到所需的結果。
由於您在代碼中使用const,因此我假設您使用的是ES2015 / ES6。 ES1015的默認函數參數允許在未傳遞任何值或未定義的情況下,使用默認值初始化形式參數。
function abc(value = []) {
const array = Array.isArray(value) ? value: [value];
}
如果使用ES6,則可以執行以下操作,它比.concat()
更干凈;
function method(value = []) {
const array = [...value];
}
value = [].concat(value ?? [])
正如@VoteyDisciple 解釋的那樣, concat function將連接單個值或 arrays 值。 如果左側的值為 null 或未定義,則空值合並運算符 (??)將使用右側的值(第二個空數組)。 所以如果 value 是 null,它會將一個空數組連接到一個空數組,返回一個空數組。
// Different inputs and outputs
values = [].concat([1,2,3] ?? []) // [1,2,3]
values = [].concat(1 ?? []) // [1]
values = [].concat(null ?? []) // []
// Wrap it in a function if you like
function array(value) {
return [].concat(value ?? [])
}
// Use it like this
values = array(values)
// Or even like this
for (let value of array(values)) {
console.log(value)
}
.flat()
的更短解決方案如果您不必檢查undefined
或null
值,還有一種更巧妙的方法。 如果之前不是數組,這基本上會將值轉換為 singleton 數組。
[value].flat()
[12].flat() // Output: [12]
[[[12]]].flat() // Output: [[12]]
如果你想刪除空值 - 只需在其上添加一個過濾器。 這將刪除所有虛假的值。
[value].filter(x => x).flat()
由於0
(和false
)是一個虛假值,如果您將數字存儲在數組中,建議將數組值與null
或undefined
進行顯式比較。
[value].filter(x => x !== null && x !== undefined).flat()
為了稍微縮短它,我們可以使用 Lodash 的isNil方法。
[value].filter(_.isNil).flat()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.