What is the best method to assign each key in an Object to the corresponding value in another Object?

Suppose I have an object called data:

{
    first: 'Zaaac',
    last: 'Ezzell',
    title: 'Mrs',
    mail: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83ece6f9f9e6efefb3c3f1e6e7e7eaf7ade0ecee">[email protected]</a>',
    cellphone: '+444444',
    phone_2: '6506679207',
    address_2: 'Holmberg',
    address_1: '34 Scott Center',
    address_3: 'Iowa City',
    address_4: 'Stephen',
    address_5: 'Iowa',
    country: 'United States',
    zipcode: '52245'
  }

I want to change each key based on a mapping object called fields:

fields:  {
  fieldName: 'map',
  fieldValue: {
    first: 'first_name',
    last: 'last_name',
    title: 'null',
    mail: 'email',
    cellphone: 'cellphone',
    phone_2: 'null',
    address_1: 'address_line_1',
    address_2: 'address_line_2',
    address_3: 'null',
    address_4: 'null',
    address_5: 'null',
    zipcode: 'null',
    country: 'country'
  }
}

For instance, whenever the key first is found in Object A, it should be changed to first_name. Similarly, replace last with last_name and so on.

I attempted the following:

await data.forEach((element) => {
      Object.keys(element).forEach(function(key) {
        console.log('Contact: ' + key + ': ' + element[key]);
        Object.keys(fields['fieldValue']).forEach(function(mapKey) {
          if (fields['fieldValue'][mapKey] !== 'null') {
            key = fields['fieldValue'][mapKey];
            console.log('LOG: KEY: ', key);
          }
        });
      });
      console.log('LOG: Element: ', element);
    });

However, the keys in the resultant Object remain unchanged.

Expected result:

{
      first_name: 'Zaaac',
      last_name: 'Ezzell',
      title: 'Mrs',
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a151f00001f16164a3a081f1e1e130e54191517">[email protected]</a>',
      cellphone: '+444444',
      phone_2: '6506679207',
      address_line_2: 'Holmberg',
      address_line_1: '34 Scott Center',
      address_3: 'Iowa City',
      address_4: 'Stephen',
      address_5: 'Iowa', 
      country: 'United States',
      zipcode: '52245'
    }

Answer №1

To transform object entries, you can utilize the fromEntries method after mapping them:

var mapKeys = { fieldName: 'map', fieldValue: { first: 'first_name', last: 'last_name', title: 'null', mail: 'email', cellphone: 'cellphone', phone_2: 'null', address_1: 'address_line_1', address_2: 'address_line_2', address_3: 'null', address_4: 'null', address_5: 'null', zipcode: 'null', country: 'country' }};

var data = { first: 'Zaaac', last: 'Ezzell', title: 'Mrs', mail: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94fbf1eeeef1f8f8a4d4e6f1f0f0fde0baf7fbf9">[email protected]</a>', cellphone: '+444444', phone_2: '6506679207', address_2: 'Holmberg', address_1: '34 Scott Center', address_3: 'Iowa City', address_4: 'Stephen', address_5: 'Iowa', country: 'United States', zipcode: '52245' };

var transformedData = Object.fromEntries(Object.entries(data).map(([key, value]) => ([mapKeys.fieldValue[key] == "null" ? key : mapKeys.fieldValue[key], value])));

console.log(transformedData);

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

What is the best way to define a variable that captures and logs the values from multiple input variables?

Hey there, I'm a new coder working on a shopping list app. I'm trying to display the input from three fields - "item", "store", and "date" - at the bottom of the page as a single line item. I attempted to do this by creating a variable called "t ...

The Homescreen.js file is not showing up as expected on the localhost/home page and is not displaying

Struggling to showcase the rooms on my hotel reservation website. Can't seem to crack it. Need some assistance, please. Spent a good 3 hours trying to figure this out. Snippet from My Homescreen.js import React ,{useState, useEffect, } from &apo ...

Determine if a specific string is present in any of the values within an array by utilizing

A scenario: I have a cookie that has been split into an array: var treats = document.cookie.split(';'); [dogs=bla, cats=sdfgh, cabbages=kjhgfdfg] If I aim to locate the index of 'cats=sdfgh', I can utilize treats.indexOf('cats= ...

Is it possible to conduct a feature test to verify the limitations of HTML5 audio on

Is there a way to detect if volume control of HTML5 audio elements is possible on iOS devices? I want to remove UI elements related to the volume if it's not alterable. After referring to: http://developer.apple.com/library/safari/#documentation/Aud ...

An error was encountered: Unable to assign value to the property "once" of [object Object] because it only has a

`Encountering an Uncaught TypeError: Cannot set property 'once' of [object Object] which has only a getter at HTMLDivElement.addEventListener (polyfills.js:1:146664). This issue is being faced during the process of upgrading the Angular version. ...

Tips for limiting the .click function to only the initial image in order to prevent loading all images within the container

I am facing a situation where multiple images are being returned into a specific div, which is working as intended. <div class="go" id="container"></div> Upon clicking on an image, it is loaded into a modal popup. However, instead of capturin ...

Identify the key in an array of objects that corresponds to the highest volume value, and return both the key and its

I am working with an array of objects that include a baseAsset key and Volume for each object, with the volume value varying between objects. My goal is to find the object with the highest volume value based on a match with the baseAsset ...

AngularJS: Modifying the template in a Directive with scoped attribute dependencies

As I delve into customizing a template within a directive and incorporating references to attributes in the parent scope, I find myself navigating through the Angular framework as a newcomer. My journey has led me to leaning on Customizing the template wit ...

What is the best method for simultaneously listening to several events?

For instance, I am interested in setting up a situation where a callback is triggered only when ALL specified events occur: on(['aEvent', 'bEvent', 'cEvent'], callback) The callback function should receive an array (or objec ...

Algorithm for detecting collisions in Javascript

I am looking to implement a collision detection function in JavaScript for canvas. Specifically, I have coin and piggy bank objects and want to create a function that triggers the disappearance of a coin object when it comes into contact with a piggy bank. ...

The AngularJS view refuses to load when accessed from the browser, although the identical code successfully loads the view on

Here is the link to my plunker where the view loads as expected on Plunker's website. Check out My First Angular Single Page Application However, after downloading the files from Plunker and unzipping them on my local machine, the view does not load ...

Updating a class within an AngularJS directive: A step-by-step guide

Is there a way to change the class (inside directive) upon clicking the directive element? The current code I have updates scope.myattr in the console but not reflected in the template or view: <test order="A">Test</test> .directive("test", ...

How to Handle Duplicate Elements in #each Svelte Block

I've encountered an issue with the related posts component on my Svelte website. While it functions correctly, there is a problem with duplicate articles showing up in the block. For example, if two articles contain three identical tags each, those ar ...

Loading your NextJS page with a full-page loader

I am looking to create a full-page loader for my NextJS app, similar to this example: https://jsfiddle.net/yaz9x42g/8/. The idea is that once the content is loaded, it should be revealed in a visually appealing way. I want to build a reusable component tha ...

Invoking a JavaScript class using a script tag

In my code, I have a class declaration in a script that is imported before the body tag: $(document).ready(function(){ var FamilyTree = function() { }; FamilyTree.prototype.displayMessage=function() { alert("test"); } }); Then, within the bo ...

Why isn't the ajax table showing up in my HTML?

I am facing an issue while trying to run an application that involves AngularJS, Ajax, and a Java Controller returning JSON. Despite my efforts, the table is not displaying in the HTML. I am new to working with Ajax and AngularJS, and need assistance troub ...

Vue.js: Optimize Webpack bundle by excluding core-js

Below is the content of my vue.config.js file: module.exports = { configureWebpack: { externals: { "vue": "Vue", "core-js": "core-js", }, }, }; By using this configuration, I have successfully excluded the vue.js (Vue) library and ...

Ways to update modal content upon clicking a button

I have a scenario where I need to display 2 modals (box1 and box2) in my code with box2 appearing on top of box1. Each modal has its own button, and I want to make sure that box1 appears first. Then, when the user clicks the button in box1, it transitions ...

Categorize messages based on the date they were last read in Angular

I am looking to organize my chat application messages by date, similar to the layout in Microsoft Teams app. Here is an example of the message data: [ { "id": 577, "source": { "userID": 56469, ...

Encountered a MongoNetworkError while attempting to establish a connection with the server at localhost:27017. The initial connection failed due to an ECONNREFUSED error at 127.0.0.1:

Encountered a MongoNetworkError: failed to connect to server [localhost:27017] on first connect [Error: connect ECONNREFUSED 127.0.0.1:27017 If I reinstall MongoDB, the code works fine. However, I am looking for a permanent solution. [error:MongoNetworkE ...