mergeri
v0.1.3
Published
A simple object merger using matcher.
Downloads
30
Maintainers
Readme
mergeri
A simple object merger using matcher.
Install
npm i mergeri
Example
Basic
const obj1 = {
a: {
b: [
{
id: 1000,
data: { a: 1 }
}
]
}
}
const obj2 = {
a: {
b: [
{
id: 999,
data: { a: 2 }
},
{
id: 1000,
data: { b: 3 }
}
]
}
}
const result = mergeri({ 'a.b.*': 'id' }, obj1, obj2)
result
{
a: {
b: [
{
id: 999,
data: { a: 2 }
},
{
id: 1000,
data: { a: 1, b: 3 }
}
]
}
}
API
mergeri(matcher, target, src1, [src2, src3...])
Matcher
Dot notation
const obj = {
a: {
b: [
{c: {d: 1 }},
{c: {d: 2 }}
]
}
}
const matcher = { "a.b.*": "c.d" }
Multiple matcher
const matchers = {
"a.*": "b.c.d" ,
"e.f.g.*": "h.i",
"x.y.*": "z",
}
Middle wildcard
const matcher = {
"a.*.c.*": "other_id"
}
Complex matcher
const matcher = {
"a.b.*": ["id", "other_id"]
}
Custom matcher
const matcher = {
"a.b.*": function(targetKey, srcKey, targetValue, srcValue, targetObj, srcObj) {
return targetValue.c.id === srcValue.c.id
}
// same as {"a.b.*": "c.id"}
}
Array merging
The default behavior is concat
. but, Custom key matcher
change the behavior to index merging.
mergeri(null, {a: [1]}, {a: [2, 3]}) // => {a: [1, 2, 3]}
mergeri({'a': (targetKey, srcKey) => targetKey === srcKey }, {a: [1]}, {a: [2, 3]}) // => {a: [2, 3]}
Last wildcard is optional.
const matcher = { 'a.b': 'id' } // => same as {'a.b.*': 'id'}
License
MIT