omi/packages/mappingjs
dntzhang 2b4b8909b8 update readme 2018-12-10 09:59:11 +08:00
..
test update readme 2018-12-10 09:52:17 +08:00
README.md update readme 2018-12-10 09:59:11 +08:00
index.js mappingjs 2.0 2018-12-09 11:15:29 +08:00
package.json update readme 2018-12-10 09:52:17 +08:00

README.md

mappingjs

Mappingjs

Tiny size objects mapping lib for javascript. Omi MVVM's best partner.

Install

npm i mappingjs

API

mapping(from, to, [rule])

  • from the object to be mapped
  • to the object mapped to
  • rule an optional parameter, mapping rules

Usage

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

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

const from = new TodoItem('task')
const to = { author: { age: 18 } }

mapping(from, to, {
  fullName: function () {
    return this.author.firstName + this.author.lastName
  }
})

So the value of to is:

{
  author: {
    firstName: "dnt",
    lastName: "zhang",
    age: 18
  },
  fullName: 'dntzhang',
  completed: false,
  text: "task"
}

→ Here's a more complex example

const res = mapping({ a: { b: 2, e: [{ f: 3 }, { f: 5 }, { f: 10 }] }, list: list }, {}, {
  'a.test': 1, //supports non function type
  'a.squareB': function () { //supports path
    return this.b * this.b
  },
  'a.e[0].squareF': function () {//supports path with arr index
    return this.f * this.f
  },
  'a.e[1].squareF': function () {//supports path with arr index
    return this.f * this.f
  },
  'a.e[2]': function () {//supports path with arr index
    return 'change array item!'
  },
  'a.e[3]': function () {//supports path with arr index
    return 'add array item!'
  },
  'list.items[*].fullName': function () {//supports * mapping all item of array
    return this.author.firstName + this.author.lastName
  },
  'list.items[*].squareTest': function () {//supports * mapping all item of array
    return this.test * this.test
  },
  'list.items[*].arr[*].squareF': function () {//supports * mapping all item of array
    return this.f * this.f
  }
})

License

MIT © dntzhang