omi/packages/mappingjs
张磊 2693e51b10 update readme 2018-11-28 10:20:53 +08:00
..
test mappingjs - update readme 2018-11-28 09:50:01 +08:00
README.md update readme 2018-11-28 10:20:53 +08:00
index.js mappingjs - fix duplicate object creation 2018-11-28 09:40:35 +08:00
package.json update package.json 2018-11-28 09:51:00 +08:00

README.md

mappingjs

Mappingjs

Objects mapping for javascript. Omi MVVM's best partner.

Install

npm i mappingjs

Usage

var a = { a: 1 }
var b = { b: 2 }

deepEqual(mapping({
  from: a,
  to: b
}), { a: 1, b: 2 })

Auto Mapping


class TodoItem {
  constructor(text, completed) {
    this.text = text
    this.completed = completed || false

    this.author = {
      firstName: 'dnt',
      lastName: 'zhang'
    }
  }
}

const res = mapping.auto(new TodoItem('task'))

deepEqual(res, {
  author: {
    firstName: "dnt",
    lastName: "zhang"
  },
  completed: false,
  text: "task"
})

Auto Mapping with init value

class TodoItem {
  constructor(text, completed) {
    this.text = text
    this.completed = completed || false

    this.author = {
      firstName: 'dnt',
      lastName: 'zhang'
    }
  }
}

const res = mapping.auto(new TodoItem('task'), { author: { a: 1 } })

deepEqual(res, {
  author: {
    firstName: "dnt",
    lastName: "zhang",
    a: 1
  },
  completed: false,
  text: "task"
})

Deep mapping


var A = { a: [{ name: 'abc', age: 18 }, { name: 'efg', age: 20 }], e: 'aaa' }
var B = mapping({
  from: A,
  to: { d: 'test' },
  rule: {
    a: null,
    c: 13,
    list: function () {
      return this.a.map(function (item) {
        return mapping({ from: item })
      })
    }
  }
})

deepEqual(B.a, null)
deepEqual(B.list[0], A.a[0])
deepEqual(B.c, 13)
deepEqual(B.d, 'test')
deepEqual(B.e, 'aaa')
deepEqual(B.list[0] === A.a[0], false)

Deep deep mapping

var A = { a: [{ name: 'abc', age: 18, obj: { f: 'a', l: 'b' } }, { name: 'efg', age: 20, obj: { f: 'a', l: 'b' } }], e: 'aaa' }
var B = mapping({
  from: A,
  rule: {
    list: function () {
      return this.a.map(function (item) {
        return mapping({
          from: item, rule: {
            obj: function () {
              return mapping({ from: this.obj })
            }
          }
        })
      })
    }
  }
})

deepEqual(A.a, B.list)
deepEqual(A.a[0].obj, B.list[0].obj)
deepEqual(A.a[0].obj === B.list[0].obj, false)

License

MIT © dntzhang