[英]How to use lodash to deep set without creating undefined values
給出這個使用lodash的例子:
var object = {};
_.set(object, [ 1, 2 ], 5);
console.log(object);
控制台中的結果對象是:
{
1: [undefined, undefined, 5]
}
現在想象一下,而不是整數2,你設置的時間戳為1445231475.你現在在一個非常大的數組中有1445231474個未定義的值,在一些_.set
操作之后將耗盡內存。
如果可能,使用_.set
,如何創建此對象:
{
1: {
2: 5
}
}
如果2真的是一個像“a”這樣的字符串,那么Lodash可能會強制“2”進入多個未定義值的數組。
如有必要,我可以使用_.merge
,但我會更興奮使用_.set
功能。
你可以用lodash setWith
做到這setWith
// unwanted behavior with set
let x = {}
_.set(x, [1,2], 'test')
// x = { '1': [ <2 empty items>, 'test' ] }
// desired behavior with setWith
let y = {}
_.setWith(y, [1,2], 'test', Object)
// y = { '1': { '2': 'test' } }
顯然, 不 ,這是不可能的,這就是為什么:
在_.set
,這是相關部分:
if (index == lastIndex) {
nested[key] = value;
} else if (nested[key] == null) {
nested[key] = isIndex(path[index + 1]) ? [] : {};
}
這里發生的是,只要路徑項不存在作為鍵,就會測試它是否是有效索引(類型為number
,或匹配/^\\d+$/
),如果是,則創建數組,否則一個東西。
因為key
是一個字符串,並且目標是設置一個名為2 (或任何其他數值)的屬性,它將始終從isIndex
返回true並將生成一個數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.