mergeri

0.1.3 • Public • Published

mergeri

A simple object merger using matcher.

npm

merge objects

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

Package Sidebar

Install

npm i mergeri

Weekly Downloads

0

Version

0.1.3

License

MIT

Unpacked Size

6.4 kB

Total Files

4

Last publish

Collaborators

  • skt-t1-byungi