_.assign 仅当属性存在于目标对象中时

新手上路,请多包涵

我的需要是做类似 _.assign 的事情,但前提是目标对象已经具有正在分配的属性。把它想象成源对象可能有一些属性可以贡献,但也有一些我不想混入的属性。

我从未使用过 _.assign 的回调机制,但尝试了以下方法。它“有效”,但它仍然将该属性分配给目标对象(未定义)。我根本不希望它分配。

 _.assign(options, defaults, initial, function (destVal, sourceVal) {
  return typeof destVal == 'undefined' ? undefined : sourceVal;
});

我编写了以下函数来执行此操作,但想知道 lodash 是否已经内置了一些更优雅的东西。

 function softMerge (dest, source) {
    return Object.keys(dest).reduce(function (dest, key) {
      var sourceVal = source[key];

      if (!_.isUndefined(sourceVal)) {
        dest[key] = sourceVal;
      }

      return dest;
    }, dest);
}

原文由 sparty02 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 462
2 个回答

你可以只拿第一个对象的键

var firstKeys = _.keys(options);

然后从第二个对象中获取一个子集对象,只获取第一个对象上存在的那些键:

 var newDefaults = _.pick(defaults, firstKeys);

然后使用该新对象作为 _.assign 的参数:

 _.assign(options, newDefaults);

或者在一行中:

 _.assign(options, _.pick(defaults, _.keys(options)));

当我在这里测试时似乎有效:http: //jsbin.com/yiyerosabi/1/edit ?js,console

原文由 ne8il 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是一个不可变的深度版本,我称之为“保留形状的合并”,在使用 lodash 的 TypeScript 中:

 function _mergeKeepShapeArray(dest: Array<any>, source: Array<any>) {
    if (source.length != dest.length) {
        return dest;
    }
    let ret = [];
    dest.forEach((v, i) => {
        ret[i] = _mergeKeepShape(v, source[i]);
    });
    return ret;
}

function _mergeKeepShapeObject(dest: Object, source: Object) {
    let ret = {};
    Object.keys(dest).forEach((key) => {
        let sourceValue = source[key];
        if (typeof sourceValue !== "undefined") {
            ret[key] = _mergeKeepShape(dest[key], sourceValue);
        } else {
            ret[key] = dest[key];
        }
    });
    return ret;
}

function _mergeKeepShape(dest, source) {
    // else if order matters here, because _.isObject is true for arrays also
    if (_.isArray(dest)) {
        if (!_.isArray(source)) {
            return dest;
        }
        return _mergeKeepShapeArray(dest, source);
    } else if (_.isObject(dest)) {
        if (!_.isObject(source)) {
            return dest;
        }
        return _mergeKeepShapeObject(dest, source);
    } else {
        return source;
    }
}

/**
 * Immutable merge that retains the shape of the `existingValue`
 */
export const mergeKeepShape = <T>(existingValue: T, extendingValue): T => {
    return _mergeKeepShape(existingValue, extendingValue);
}

一个简单的测试,看看我认为这样的合并应该如何工作:

 let newObject = mergeKeepShape(
    {
        a : 5,
        // b is not here
        c : 33,
        d : {
            e : 5,
            // f is not here
            g : [1,1,1],
            h : [2,2,2],
            i : [4,4,4],
        }
    },
    {
        a : 123,
        b : 444,
        // c is not here
        d : {
            e : 321,
            f : 432,
            // g is not here
            h : [3,3,3],
            i : [1,2],
        }
    }
);
expect(newObject).toEqual({
    a : 123,
    // b is not here
    c : 33,
    d : {
        e : 321,
        // f is not here,
        g : [1,1,1],
        h : [3,3,3],
        i : [4,4,4]
    }
});

我在测试中使用了 seamless-immutable 自己,但没有看到需要把它放在这个答案中。

我特此将其置于公共领域。

原文由 Ciantic 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题