omi/packages/mappingjs
dntzhang 1d5c30f841 mappingjs - sync array length when auto mapping 2018-12-07 09:39:01 +08:00
..
test mappingjs - update readme 2018-11-28 09:50:01 +08:00
README.md update tutorial of mvvm 2018-11-29 13:20:59 +08:00
index.js mappingjs - sync array length when auto mapping 2018-12-07 09:39:01 +08:00
package.json mappingjs - sync array length when auto mapping 2018-12-07 09:39:01 +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

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

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

Manual 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)

Manual 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)

Other example

const testObj = {
  same: 10,
  bleh: 4,
  firstName: 'dnt',
  lastName: 'zhang',
  a: {
    c: 10
  }
}

const vmData = mapping({
  from: testObj,
  to: { aa: 1 },
  rule: {
    dumb: 12,
    func: function () {
      return 8
    },
    b: function () {
      return mapping({ from: this.a })
    },
    bar: function () {
      return this.bleh
    },
    fullName: function () {
      return this.firstName + this.lastName
    },
    'd[2].b[0]': function () {
      return this.a.c
    }
  }
})

License

MIT © dntzhang