Skip to content

Instantly share code, notes, and snippets.

@meigwilym
Last active September 26, 2018 09:31
Show Gist options
  • Save meigwilym/76659e1436dadf5905a96bda227e6911 to your computer and use it in GitHub Desktop.
Save meigwilym/76659e1436dadf5905a96bda227e6911 to your computer and use it in GitHub Desktop.
Use array functions rather than loops for JSON objects

Use array functions rather than loops for JSON objects

Take this array of tag objects for example.

const tags = [
	{
		name: 'Studio',
		id: 'studio',
		url: '/tags/studio'
	},
	{
		name: 'Lab',
		id: 'lab',
		url: '/tags/lab'
	},
	{
		name: 'Showroom',
		id: 'showroom',
		url: '/tags/showroom'
	}
];

I want to get a tag with a certain id value. In the past I would have used a loop, returning the object when found.

var id = 'lab';
for(var i in tags) {
	if(tags[i].id == id) {
		return tags[i];
	}
}

A better way is to use two of Array's built in functions, filter and reduce.

Filter can check the id value for you and only return that object.

const id = 'lab';
let tag = tags.filter(t => t.id == id);

Console logging tag would show an array of one tag object. We could use this with tag[0] but it's ugly.

So we use reduce to reduce that array (of one value) to just a plain value. This is simple.

tag = tag.reduce(e => e);

or as a one liner:

const tag = tags.filter(t => t.id == id).reduce(e => e);

Array.reduce would usually combine the array's values into one, but as our array only contains one value, the reducer function simply returns it. Remember that e => e is just shorthand for

function(element) {
	return element;
}

Any time I handle arrays in Javascript, the first tools to reach for are map, filter and reduce. I suggest you do the same.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment