Is reduce an alternative to using map when I want to transform one array into another with _.lodash?

StackOverflow https://stackoverflow.com/questions/21422789

  •  04-10-2022
  •  | 
  •  

Question

Given the object that we have created:

var t2 = 
[
 {"topicId":1,"subTopicId":1,"topicName":"a","subTopicName":"11"},
 {"topicId":2,"subTopicId":x,"topicName":"b","subTopicName":"xx"},
 {"topicId":3,"subTopicId":y,"topicName":"c","subTopicName":"yy"}
]

How can we map this to give:

var t2 = 
    [
      {"id":1,"name":"a"},
      {"id":2,"name":"b"},
      {"id":3,"name":"c"},
    ]

I understand _.lodash has a map function and a reduce. Could we use either for doing this?

Note that in a previous question my team mates was given this as a solution:

var dataMap = {
        topicId: 'id',
        topicName: 'name'

    };

var finalT = t.map(function (topic) {
    var t = {};
    for (var key in dataMap) {
        t[dataMap[key]] = topic[key];
    };
    return t;
});

Is there a simpler way that I could do this? The mapping part seems to be not so simple.

Was it helpful?

Solution 2

I understand _.lodash has a map function and a reduce. Could we use either for doing this?

Yes, since reduce is the most generic iteration method, map can be expressed via reduce. It's not necessary here, though.

Is there a simpler way that I could do this? The mapping part seems to be not so simple.

Try to understand what it does. It creates a new object, and iterates the dataMap to see which properties should be copied whereto.

You can leave that property-mapping-descriptor-loop away and do explicitly/verbosely

var finalT = t.map(function (topic) {
    return {
        id: topic.topicId,
        name: topic.topicName
    };
});
// or, with your variable names and lodash:
t2 = _.map(t2, function (topic) {
    return {
        id: topic.topicId,
        name: topic.topicName
    };
});

OTHER TIPS

Try this:

var t2 = t2.map(function (e) {
  return {id: e.topicId, name:e.topicName};
});

Notice that the callback function of map accepts each element of collection(in this case, each element of array) and transform it to the form what you want.

JavaScript array already has map function. Refer to this URL: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top