Ron*_*dot 3 javascript ecmascript-6 lodash
找到了用于vanilla js实现的出色代码_.get
:
const get = (obj, path, defaultValue) => path.split(".")
.reduce((a, c) => (a && a[c] ? a[c] : (defaultValue || null)), obj)
Run Code Online (Sandbox Code Playgroud)
现在,我正在寻求_.set
实施,任何帮助将不胜感激。
我认为这可以解决:
const set = (obj, path, value) => {
if (Object(obj) !== obj) return obj; // When obj is not an object
// If not yet an array, get the keys from the string-path
if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || [];
path.slice(0,-1).reduce((a, c, i) => // Iterate all of them except the last one
Object(a[c]) === a[c] // Does the key exist and is its value an object?
// Yes: then follow that path
? a[c]
// No: create the key. Is the next key a potential array-index?
: a[c] = Math.abs(path[i+1])>>0 === +path[i+1]
? [] // Yes: assign a new array object
: {}, // No: assign a new plain object
obj)[path[path.length-1]] = value; // Finally assign the value to the last key
return obj; // Return the top-level object to allow chaining
};
// Demo
var obj = { test: true };
set(obj, "test.1.it", "hello");
console.log(obj); // includes an intentional undefined value
Run Code Online (Sandbox Code Playgroud)
它比复杂得多get
,因为需要一些逻辑来创建对象中路径的缺失部分,覆盖阻碍该过程的原始值,并确定新的子项最好是数组还是普通的宾语。
归档时间: |
|
查看次数: |
832 次 |
最近记录: |