When working with Javascript then very often you will have the need to pass object into a method, so some processing with it, i.e add new fields or change existing fields and then return the object.

Doing this is not very safe or clean since in Javascript objects are passed by reference and it means that you can manipulate object state and cause some strange things to happen.

Recently my collegue introduced to me more cleaner and functional way to do this. I had some troubles at first wrapping my head around it but after it clicked I find it quite useful and use it every time I need to manipulate an object.

Lets say for example I have object animals which holds the count of each animal I own:

const animalCounts = {
	chicken: 10,
	cow: 15,
	dog: 100,
	lemming: 12
}

Then I have another object which has the prices for these animals:

const animalPrices = {
	chicken: 10,
	cow: 82,
	dog: 100000,
	lemming: 900
}

Now I need to calculate the price for each of the animals to know how much my inventory is worth.

One way around it is to use the existing object and create a new object and return that.

const calculateAnimalValues = (animalCounts, animalPrices) => {
	const animalValues = {};

	Object.keys(animalCounts).forEach(key => {
		const animalPrice = animalPrices[key];
		const animalCount = animalCounts[key];
		if (animalPrice && animalCount) {
			const totalValue = animalPrice * animalCount;
			animalValues[key] = totalValue;
		}
	});

	return animalValues;
}

console.log(calculateAnimalValues(animalCounts, animalPrices));

In this example I create array from the object and then loop over the array with forEach, do some calculation and then assign keys to the object that will be returned from the calculateAnimalValues method. This method works but it has some issues - you need to check values or remove undefined values later etc.

The other way would be to use Object.fromEntries and Object.entries. This would look like this:

const calculateAnimalValues = (animalCounts, animalPrices) =>
	Object.fromEntries(
		Object.entries(animalCounts)
			.map(([key, value]) => {
				const animalPrice = animalPrices[key]
				return [key, (animalPrice * value)];
			})
	)

Here we are creating new Object from key value pairs returned from Object.entries. Its more shorter and more powerful. You can chain all JS array methods before or after the map method etc.