2

How I can update an array element values with another array elements data values, using Lodash

var Master_Array [
{ Name: "Jon", Region: "North America & Caribbean" },
{ Name: "Ruan", Region: "Asia Pacific" }
]

var Regions_Map = [
{ Region: 'Europe', NewRegion: 'EMEA' },
{ Region: 'North America & Caribbean', NewRegion: 'NAC' },
{ Region: 'Asia Pacific', NewRegion: 'APAC' }
]

I think that can be did with:

_.chain()
.mapValues( ...blá blá... )
.values()
.value();

Expected result:

var Master_Array [
{ Name: "Jon", Region: "NAC" },
{ Name: "Ruan", Region: "APAC" }
]

3 Answers 3

2

you don't need to execute mapValues as you are iterating a collection and not an object, mapKeys and mapValues is preferable iterating objects and mapped to another

Now, approach 1, if you want to run something that will return a new array of your expected items then try with map like this

var EXPECTED_RESULT = _.map(Master_Array, function(item){
    var newItem = {};
    newItem.Name = item.Name;
    newItem.Region = _.find(Regions_Map, {Region: item.Region}).NewRegion
    return newItem;
});

and if you want to modify the existing array, then just loop over it either by loadash or normal javascript loop, and perform the operation

_.each(Master_Array,function(item){
    item.Region = _.find(Regions_Map, {Region: item.Region}).NewRegion
} )
Sign up to request clarification or add additional context in comments.

Comments

1

A solution with map and find:

var Master_Array = [
{ Name: "Jon", Region: "North America & Caribbean" },
{ Name: "Ruan", Region: "Asia Pacific" }
];

var Regions_Map = [
{ Region: 'Europe', NewRegion: 'EMEA' },
{ Region: 'North America & Caribbean', NewRegion: 'NAC' },
{ Region: 'Asia Pacific', NewRegion: 'APAC' }
];

Master_Array = Master_Array.map((person) => ({
  Name: person.Name,
  Region: Regions_Map.find((region) => region.Region === person.Region).NewRegion
}));

console.log(Master_Array);

Comments

0

A javascript solution

var Master_Array = [
{ Name: "Jon", Region: "North America & Caribbean" },
{ Name: "Ruan", Region: "Asia Pacific" }
];
var Regions_Map = [
{ Region: 'Europe', NewRegion: 'EMEA' },
{ Region: 'North America & Caribbean', NewRegion: 'NAC' },
{ Region: 'Asia Pacific', NewRegion: 'APAC' }
];


var result = [];
Master_Array.forEach(function(data){
  var temp = Regions_Map.filter(function(map){
    if(map.Region === data.Region){
      return map;
    }
  });
  if(temp){
  result.push({
        Name : data.Name,
        NewRegion: temp[0].NewRegion
      });
  }
});

console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.