1.0.2 • Published 3 years ago

fastest-object-formatter v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

Fastest-object-formatter

This is the zero dependency object formatter. It uses provided schemas to format object.

Note: you should first compile formatter because it will be created with Function constructor. It is expensive enough, but compiled formatter will be high performance. Do not compile formatter every time if you need high performance

Install

npm install fastest-object-formatter

Example

const generateFormatter = require('fastest-object-formatter');

const testInputObject = {
	user: {
		id: 111,
		accounts: [
			{
				name: 'Super'
			}
		]
	},
	age: {
		test: 200
	},
	foo: null
};

const keyMap = {
	'user.id': 'anotherUser.id',
	'user.accounts[0].name': 'deep.object.hello.name',
	'age.test': 'rainbow',
	'foo': 'hi.how.you.bar'
};

const formatter = generateFormatter(keyMap);
const resultFormattedObject = {};
formatter(testInputObject, resultFormattedObject);
console.log(JSON.stringify(resultFormattedObject, null, 2))
/*
Expected output:
{
  "anotherUser": {
    "id": 111
  },
  "deep": {
    "object": {
      "hello": {
        "name": "Super"
      }
    }
  },
  "rainbow": 200,
  "hi": {
    "how": {
      "you": {
        "bar": null
      }
    }
  }
}
*/

Example with custom predicate

const generateFormatter = require('fastest-object-formatter');

const testInputObject = {
	user: {
		id: 111,
		accounts: [
			{
				name: 'Super'
			}
		]
	},
	age: {
		test: 200
	},
	foo: null
};

const keyMap = {
	'user.id': 'anotherUser.id',
	'user.accounts[0].name': 'deep.object.hello.name',
	'age.test': 'rainbow',
	'foo': 'hi.how.you.bar'
};

const formatter = generateFormatter(keyMap, (value) => value !== null);
const resultFormattedObject = {};
formatter(testInputObject, resultFormattedObject);
console.log(JSON.stringify(resultFormattedObject, null, 2));
/*
Expected output:
{
  "anotherUser": {
    "id": 111
  },
  "deep": {
    "object": {
      "hello": {
        "name": "Super"
      }
    }
  },
  "rainbow": 200
}
*/
1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago