path.split(".-6ren">
gpt4 book ai didi

lodash "set"方法的 javascript 实现

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:20:30 26 4
gpt4 key购买 nike

找到 this excellent code对于 _.get vanilla js 实现:

const get = (obj, path, defaultValue) => path.split(".")
.reduce((a, c) => (a && a[c] ? a[c] : (defaultValue || null)), obj)

现在我正在寻找_.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

它比 get 稍微复杂一点,因为需要一些逻辑来创建对象中路径的缺失部分,覆盖阻碍的原始值,并确定是否一个新的 child 最好是一个数组或一个普通对象。

关于lodash "set"方法的 javascript 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54733539/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com