Skip to content

Object transformations

Robert Biro edited this page Oct 12, 2016 · 1 revision

Deflate

Takes a JavaScript object and squashes its nested objects and arrays into a single level:

Mangler.deflate(object[, options])
  • object is the object to flatten
  • options is an object with optional parameters

Example object:

o = {
	user: {
		id: 'jsmith',
		name: 'John Smith',
		roles: ['Admin', 'User']
	}
};

When called without options, it will completely flatten the object:

Mangler.deflate(o);

/*
	o = {
		user_id: "jsmith",
		user_name: "John Smith",
		user_roles_0: "Admin",
		user_roles_1: "User"
	}
*/

Optionally, it can be limited to only take a certain number of iterations from the root:

Mangler.deflate(o, { limit: 1 });

/*
	o = {
		user_id: "jsmith",
		user_name: "John Smith",
		user_roles: ["Admin", "User"],
	}
*/

By default it generates snake_case property names for deflated items, specify the transform option to use one of the supported text transformations. See String transforms for details.

Mangler.deflate(o, { transform: 'camel' });

/*
	o = {
		userId: "jsmith",
		userName: "John Smith",
		userRoles0: "Admin",
		userRoles1: "User"
	}
*/

Object properties will be deflated in-place, clone the object first if you need the original structure, or reverse it with...

Inflate

Reverses the effect of deflate. When called on the first two results above without options, it restores the original object.

Mangler.inflate(o);

With the limit option, you can limit processing to a certain number of levels, starting from the last word of the property name:

Mangler.inflate(o, { limit: 1 });

/*
	o = {
		user: {
			id: "jsmith"
			name: "John Smith"
		},
		user_roles: ["Admin", "User"]
	}
*/

You can also use the transform option to run the resulting property names through .transform(), and the from option to change how words are detected in property names. Both of these options default to snake_case.

As usual, you can call the .inflate() and .deflate() methods on Mangler() object collections as well to apply them to all items, just leave out the first parameter.

Learning Mangler.js

Optional Modules

Reference

Clone this wiki locally