Created
May 8, 2015 13:52
-
-
Save ca0v/3b69ba5f1bd60affd9a5 to your computer and use it in GitHub Desktop.
deep-extend array merge when key values exist
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function merge(key: string, ...arrays: Array<any>[]) { | |
// skip trivial arrays | |
arrays = arrays.filter(a => !!a && 0 < a.length); | |
var result = arrays.shift(); | |
if (!arrays.length) return result; | |
var hash = {}; result.forEach((item, i) => hash[item.id] = i); | |
arrays.forEach(array => { | |
array.forEach(item => { | |
var id = item[key]; | |
if (typeof hash[id] === "undefined") { | |
hash[id] = result.push(item) - 1; | |
} else { | |
result[hash[id]] = deepExtend(result[hash[id]], item); | |
} | |
}); | |
}); | |
return result; | |
} | |
/* | |
Modify deepExtend to call merge when two arrays are encountered: | |
} else if (Array.isArray(val)) { | |
target[key] = merge("id", target[key], deepCloneArray(val)); | |
return; | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment