首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >lodash "set“方法的javascript实现

lodash "set“方法的javascript实现
EN

Stack Overflow用户
提问于 2019-02-17 21:03:14
回答 3查看 5.4K关注 0票数 9

找到_.get普通js实现的this excellent code

代码语言:javascript
运行
复制
const get = (obj, path, defaultValue) => path.split(".")
.reduce((a, c) => (a && a[c] ? a[c] : (defaultValue || null)), obj)

现在我正在寻找_.set的实现,任何帮助都将不胜感激。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-02-17 21:30:42

我认为这可以涵盖它:

代码语言:javascript
运行
复制
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更复杂,因为需要一些逻辑来创建对象中缺少的路径部分,覆盖阻碍路径的原始值,以及确定新子对象更好地应该是数组还是普通对象。

票数 16
EN

Stack Overflow用户

发布于 2020-01-13 16:06:24

检查这一条:

代码语言:javascript
运行
复制
/**
 * @example
 * const obj = {id:1, address: {city: 'Minsk', street: 'Prityckogo 12'}}
 * setByString(obj, 'address.city', 'Grodno'); obj.address.city => 'Grodno'
 * setByString(obj, ['address', 'city'], 'Grodno'); obj.address.city => 'Grodno'
 * setByString(obj, ['address', city', 'phones'], {mobile: 1234, home: 222}); obj.address.city.phones.home => 222
*/

/**
* @param    {any}   input
* @return   {boolean}
*/

const isObject = (input) => (
  null !== input && 
    typeof input === 'object' &&
    Object.getPrototypeOf(input).isPrototypeOf(Object);
)

 **/
 * @param   {object}    obj
 * @param   {string}    path
 * @param   {any}       value
 */

const setByString = (obj, path, value) => {
  const pList = Array.isArray(path) ? path : path.split('.');
  const len = pList.length;
  // changes second last key to {}
  for (let i = 0; i < len - 1; i++) {
    const elem = pList[i];
    if (!obj[elem] || !isObject(obj[elem])) {
      obj[elem] = {};
    }
    obj = obj[elem];
  }

  // set value to second last key
  obj[pList[len - 1]] = value;
};
票数 3
EN

Stack Overflow用户

发布于 2020-11-30 18:50:34

代码语言:javascript
运行
复制
const set = (obj = {}, paths = [], value) => {
    const inputObj = obj === null ? {} : { ...obj };

    if (paths.length === 0) {
        return inputObj;
    }

    if (paths.length === 1) {
        const path = paths[0];
        inputObj[path] = value;
        return { ...inputObj, [path]: value };
    }

    const [path, ...rest] = paths;
    const currentNode = inputObj[path];

    const childNode = set(currentNode, rest, value);

    return { ...inputObj, [path]: childNode };
};

示例: const input = {};

set(input,'a','b','hello');

结果:{ a:{ b:'hello‘}}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54733539

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档