Sunday 2 April 2017

Adding fields in a js functional pipeline

I have an array of objects with a set of fields in node.js. Lets say

let arr = [ {a:1,b:2}, {a:3,b:6}]

I would like to extend all objects and assign to a new variable. My naïve approach is like the following way

let arr2 = arr.map(x => x.c = x.a + x.b )

However, the arrow function returns the x.a+x.b value, instead of the x object, so this won't work as I hope. It also alters the arr in place which is very nonfunctional and confusing.

I'm relatively new to js so maybe I'm thinking wrong from the beginning. What is the idiomatic js expression for this kind of object extension?



via LudvigH

No comments:

Post a Comment