Write a pure function to return one object from internal properties to other objects?

Performing some data conversion exercises and getting stuck. I have an object that I want to convert to look like the output from (starting) β†’ to (expected ending) , described below. I am trying to use Array.reduce and Object.assign to keep the output clean. but I just can't get it to work correctly.

 /** * from (starting): {topic: {id: 2}, products: {id: 3}} * to (expected ending): {topic: 2, products: 3} */ const starting = {topic: {id: 2}, products: {id: 3}}; const ending = Object.keys(starting).reduce((p, key) => { if(!p[key]) p[key] = key; return Object.assign(p[key], starting[key].id); }, {}) 
+7
javascript arrays reduce transformation
source share
4 answers

You can use reduce , just remember to return the starting object after each iteration.

 function convert(start) { return Object.keys(starting).reduce((o, key) => { o[key] = start[key].id; return o; }, {}); } const starting = {topic: {id: 2}, products: {id: 3}}; console.log(convert(starting)); 
+7
source share

Try the following:

 var starting = {topic: {id: 2}, products: {id: 3}}; var ending = Object.keys(starting).reduce((p, key) => { p[key] = starting[key].id; return p; }, {}) 

This will create a new object, so there is no need for Object.assign , etc. to keep the output clean.

+3
source share

I don't think reduce() is the right tool for this.

Try iterating with starting with forEach() instead:

 const starting = {topic: {id: 2}, products: {id: 3}}; const ending = {}; Object.keys(starting).forEach(p => ending[p] = starting[p].id); console.log(ending); 
+2
source share

A solution with a pure function will require that you return a new object at each iteration:

 function convert(start) { return Object.keys(starting).reduce((o, key) => Object.assign({}, { [key]: start[key].id }, o), {}); } const starting = {topic: {id: 2}, products: {id: 3}}; console.log(convert(starting)); 

Using the distribution of an object makes it cleaner:

 function convert(start) { return Object.keys(starting).reduce((o, key) => ({ ...o, [key]: start[key].id }), {}); } const starting = {topic: {id: 2}, products: {id: 3}}; console.log(convert(starting)); 
+2
source share

All Articles