当前位置: 首页 > 文档资料 > Lazy.js 英文文档 >

merge

优质
小牛编辑
129浏览
2023-12-01

Produces an ObjectLikeSequence consisting of all the recursively merged values from this and the given object(s) or sequence(s).

Note that by default this method only merges "vanilla" objects (bags of key/value pairs), not arrays or any other custom object types. To customize how merging works, you can provide the mergeFn argument, e.g. to handling merging arrays, strings, or other types of objects.

Signature

ObjectLikeSequence.merge = function(others, mergeFn) { /*...*/ }
ObjectLikeSequence.merge = function merge(var_args) {
  var mergeFn = arguments.length > 1 && typeof arguments[arguments.length - 1] === "function" ?
arrayPop.call(arguments) : null;
  return new MergedSequence(this, arraySlice.call(arguments, 0), mergeFn);
}
NameType(s)Description
others...Object|ObjectLikeSequence

The other object(s) or sequence(s) whose values will be merged into this one.

mergeFnFunction?

An optional function used to customize merging behavior. The function should take two values as parameters and return whatever the "merged" form of those values is. If the function returns undefined then the new value will simply replace the old one in the final result.

returnsObjectLikeSequence

The new sequence consisting of merged values.

Examples

// These examples are completely stolen from Lo-Dash's documentation:
// lodash.com/docs#merge

var names = {
  'characters': [
{ 'name': 'barney' },
{ 'name': 'fred' }
  ]
};

var ages = {
  'characters': [
{ 'age': 36 },
{ 'age': 40 }
  ]
};

var food = {
  'fruits': ['apple'],
  'vegetables': ['beet']
};

var otherFood = {
  'fruits': ['banana'],
  'vegetables': ['carrot']
};

function mergeArrays(a, b) {
  return Array.isArray(a) ? a.concat(b) : undefined;
}

Lazy(names).merge(ages); // => sequence: { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] }
Lazy(food).merge(otherFood, mergeArrays); // => sequence: { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }

// ----- Now for my own tests: -----

// merges objects
Lazy({ foo: 1 }).merge({ foo: 2 }); // => sequence: { foo: 2 }
Lazy({ foo: 1 }).merge({ bar: 2 }); // => sequence: { foo: 1, bar: 2 }

// goes deep
Lazy({ foo: { bar: 1 } }).merge({ foo: { bar: 2 } }); // => sequence: { foo: { bar: 2 } }
Lazy({ foo: { bar: 1 } }).merge({ foo: { baz: 2 } }); // => sequence: { foo: { bar: 1, baz: 2 } }
Lazy({ foo: { bar: 1 } }).merge({ foo: { baz: 2 } }); // => sequence: { foo: { bar: 1, baz: 2 } }

// gives precedence to later sources
Lazy({ foo: 1 }).merge({ bar: 2 }, { bar: 3 }); // => sequence: { foo: 1, bar: 3 }

// undefined gets passed over
Lazy({ foo: 1 }).merge({ foo: undefined }); // => sequence: { foo: 1 }

// null doesn't get passed over
Lazy({ foo: 1 }).merge({ foo: null }); // => sequence: { foo: null }

// array contents get merged as well
Lazy({ foo: [{ bar: 1 }] }).merge({ foo: [{ baz: 2 }] }); // => sequence: { foo: [{ bar: 1, baz: 2}] }