Utilizing Lodash to update values of elements by chaining or mapping from a different array

How can I update the values of elements in an array with data values from another array, 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 believe this can be accomplished with:

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

Expected outcome:

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

Answer №1

When iterating over a collection, there is no need to use mapValues. This method is more suitable for iterating over objects and mapping them to another.

For the first approach, if you want to create a new array with your desired items, you can use map as shown below:

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;
});

If you wish to modify the existing array, you can loop over it using lodash or regular JavaScript loop and perform the necessary operations.

_.each(Master_Array,function(item){
    item.Region = _.find(Regions_Map, {Region: item.Region}).NewRegion
} )

Answer №2

One way to approach this problem is by using the combination of map and find:

var Employees = [
{ 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' }
];

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

console.log(Employees);

Answer №3

Here is a clever javascript code 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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on Adding Tawk.to Widget to Your Next.JS Website

I followed the instructions on their @tawk.to/tawk-messenger-react plugin documentation, but I am still facing issues. I created a component named /components/Chat.js import TawkMessengerReact from "@tawk.to/tawk-messenger-react"; export defaul ...

Angular not recognizing draggable true functionality

I am encountering an issue with a div element: <div draggable = "true" ng-show="showPullDown" class="topPull stretch" draggable > </div> The draggable=true attribute is not functioning as expected. I have attempted to set it through the co ...

Using Laravel to set cookies with Ajax

I am facing difficulties in setting cookies through laravel using ajax. Despite reading several questions and posts, I have not been able to find a solution. My issue involves a dropdown that triggers a javascript function to send its value to a controlle ...

Is Jacksson up to the task of managing enums?

Imagine having an enum type called Gender. @Enumerated(EnumType.STRING) private Gender gender; Can the Jackson JSON parser successfully assign a value to this field from a JSON string? ...

Could you offer assistance in resolving the error I am encountering with the collection.get() function?

I encountered an issue while trying to implement a database in my project. I imported 'collection' to use in my code. Here is the snippet: import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js"; import ...

Switch the checkbox to a selection option

Is there a way to switch the selection method from checkboxes to a dropdown menu? $("input[name=koleso]:first").prop("checked", true); $('body').on('click', '.koleso label', function (e) { koles ...

What is the reason for AngularJS's inclusion of a colon at the end of a data object in an $http post

While attempting to utilize angular js $http for sending a post request to elasticSearch, I encounter an "Unexpected token : " Error. Here is a snippet of my code: var request= $http({ method: "post", url: path, accept:"*/*", headers:{"Co ...

The error message says: "VueComponent.filterKategori function cannot read property 'filter' because it is undefined at line 16260 in app.js."

this is the code snippet that I'm dealing with: computed: { filterKategori() { var kategori = this.kategori.data.filter(f => { return f.induk == null && f.id_klasifikasi == this.id_klasifikasi; }); return kat ...

The 401 error code does not provide a JSON response

Here is an example of using Phalcon to create an API: $response = new Response(); $response->setStatusCode( 401, 'Unauthorized' ); $response->setContentType( 'application/json', 'UTF-8' ); $response->setJsonContent( ...

Developing a matrix array in Python

I am attempting to construct a 2-dimensional matrix using an array, but I haven't fully grasped it yet. This is what I have tried: for i in range(x): for k in range(y): array.array('u', [i] : [k]) My goal is to create a field with x as th ...

Activating Anchor's Pseudo Content on Hover of Another Element

I've encountered a straightforward issue - I have an anchor in a navigation menu that generates an arrowhead character as ::after pseudo content in CSS when hovering over it: https://i.sstatic.net/Yhd9A.jpg However, the arrowhead character disappear ...

Make the background disappear when the text field is left empty and the cursor is not present (onUnfocus)

When the text field is empty and there is no cursor in the text field, I want it to be transparent and for the spell checker not working. The result should be displayed a little to the left inside a <div>. Should this be done using CSS, JavaScript, ...

Embed API requests using JavaScript's Axios library to ensure the correct promise is returned

I am currently facing an issue with posting data to my API using axios. In order to make the request, I need to include a XSFR-token along with it. The technologies I am using for this are React, Redux, Thunk, and Axios. The problem lies in handling this ...

Remove information using Axios in ReactJS by interacting with an API

I have successfully pulled data from the jsonplaceholder API and stored it in my state. However, I am struggling with implementing the deleteContact() method to remove the data. Can anyone provide guidance on how to properly execute the deleteContact() met ...

Employing getters in the toObject() method

As I delve into the code of a Node.js Express application for learning purposes, I came across the following line that sparked my curiosity regarding the inclusion of getters and virtuals. var pgmsDbObj = chnnlList[chnnlIndex] var pgmsObj = pgmsDbObj.to ...

What are some effective strategies for bypassing CORS requirements in Vue client-side and server-side applications?

I found this amazing MEVN stack tutorial that I've been following: MEVN Stack Tutorial The tutorial is about creating a blog post app, where the client side is built using Vue (referred to as app A) and the backend is built on Express.js providing d ...

Vanish and reappear: Javascript block that disappears when clicked and shows up somewhere else

My goal is to make three squares randomly disappear when clicked on the page. However, I am facing an issue where some of them, usually the 2nd or 3rd one, reappear elsewhere on the page after being clicked. I have created a jsfiddle to demonstrate this: ...

Issues with Firebase-admin preventing writing to the database are occurring without any error messages being displayed

Issues with Firebase admin writing to the database. The database is instantiated as follows: var db = admin.database(); A reference to the desired table is then set up: var systemsRef = db.ref("systems/"); A function is created to check if a 'sys ...

Decoding JSON data using Ruby on Rails

Although this topic has been discussed at length, I am struggling to grasp the basics. As a newcomer to JSON, everything seems new and unfamiliar to me. My goal is to extract data from a JSON feed located on a remote server and integrate it into my rails3 ...

Verify the position of the scrollbar without triggering any reflow

Here is a function I have: is_bottom: function() { if (settings.scrollBottomOffset === -1) { return false; } else { var scroll_height, scroll_top, height; scroll_height = ...