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

Tips for utilizing various broadcast options to trigger Angular controllers according to the user's chosen selection

I'm currently developing an angularjs application that includes multiple date range pickers on a single web page. When a user selects a date range from one of these pickers, I need to send the selected dates to the corresponding angular controller ass ...

Failed to decipher an ID token from firebase

I'm feeling extremely frustrated and in need of assistance. My goal is to authenticate a user using Google authentication so they can log in or sign up. Everything worked perfectly during development on localhost, but once I hosted my app, it stopped ...

Having difficulties integrating a login solution due to an error saying "eslint Promise executor functions should not be async no-async-promise-executor"

I'm currently working on integrating a login solution into my Vue app using the JWT Authentication plugin. While I have a test solution that is functional, I'm facing an issue in my main branch where the eslint version seems to be causing an err ...

How can I generate a list of JavaScript files to be included in a template for both production and development environments using Grunt?

I need a way to organize a list of JavaScript files in one central location, either within gruntfile.js or an external JSON file, and then dynamically implement it into a template for both development and production environments. List of JavaScript files: ...

Vue JS: dynamic reactive structure

As I delved into understanding the basics of reactivity and its syntax, I encountered an interesting problem. Take a look at this code snippet: const app = Vue.createApp({ data: dataFunction, methods: {method1: methodImpl} }) var dataObj = { tit ...

Guide for creating a function that accepts an array containing multiple arrays as input

I am working with a function called drawSnake and it is being invoked in the following manner: drawSnake( [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], ] ); How should I format the input for this function? I have attempted using Array<Array<[numb ...

What steps can I take to ensure a JavaScript loading image is displayed until the entire page has finished loading?

Looking to implement a JavaScript loading image that displays until the page has fully loaded? I'm currently developing an online antivirus scanner and in need of help. I am trying to set up JavaScript to show a loading image while a file is being up ...

When a menu item is clicked, apply a class and change the display property to

I currently have an HTML menu with a submenu structured as follows: <li id="item-3" class="menu-item has-children-3"> <a href="#" class="sf-with-ul"><span>Auto</span></a ...

Tips for utilizing the simple-peer module within a Node.js environment?

I recently started using Node.js and I'm interested in incorporating the simple-peer module into my application. However, I am struggling to understand how to implement it based on the provided documentation. Are there any resources available that can ...

What is the process for filtering records by a date greater than in the Material Table?

How can I filter the Material table by date values greater than the current value? I've been able to filter by exact date so far, but I need to filter all values that are greater than or equal to the current value in the table. <TableMaterial ...

Enhancing jQuery Component while making an Ajax request

When a user clicks a button, I am making an ajax call to send out multiple emails. My goal is to update a "Please wait..." div before and after the call with status updates, as well as report any errors that may occur. However, I have encountered an issue ...

Retrieve identical values from an array and display them using Vue.js

I am working with a product array that includes id, name, and category data for 5 products. For example, let's say there are 3 products assigned to the mobile category and 2 products assigned to the computer category. What is the best approach to rend ...

Tips for eliminating checkboxes from a form

function addCheckbox(){ var labels = document.form1.getElementsByTagName('label'); var lastLabel = labels[labels.length-1]; var newLabel = document.createElement('label'); newLabel.appendChild(Checkbox(labels.length)); ...

Trouble with exporting and importing an Express application

Starting with a simple Express example of 'Hello World', I am looking to refactor the code into separate files for configuration and routing. var express = require('express'); var app = express(); app.get('/', function (req, ...

Instantly reveal menu by pressing button

Is there a way to make my mobile menu open immediately upon touching the button? I have used ontouchstart="" in both buttons to create an overlay on the content when the offcanvas menu is visible. This functions well as soon as the user touches either butt ...

Utilizing arrays in the label field of Chart.js

Creating a straightforward bar chart using Chartjs 3.x The process involves fetching JSON data from the server, parsing it, and storing specific parts in arrays. See the code snippet below: serverData = JSON.parse(http.responseText); console.log(serverDa ...

The Bootstrap Navbar is causing the navigation bar to span across two lines

I'm having an issue with my navbar taking up two lines on desktop resolution, but fitting perfectly on mobile. I've spent hours going through the code with no success. Any help would be greatly appreciated. The HTML code is provided below. <! ...

Does the require function in nodejs have any connection to the package.json file?

If 'random_module' is included in the list of dependencies in my package.json file, can I use the code var rm = require("random_module"); to access it? Essentially, does the argument for require function apply to any module listed under the depen ...

Issue with React and JavaScript: Object is displayed on the console briefly before disappearing

I am having an issue with my sign up page where the console log of the two fields disappears after a second. I would appreciate any assistance on this matter. Below is the code for the sign-up form: export default function SignUp() { const [firstNam ...

Is there a way to bring in a variable from the front end script?

Is it possible to transfer an array of data from one HTML file to another? If so, how can this be done? Consider the following scenario: First HTML file <script> let tmp = <%- result %>; let a = '' for (const i in tmp){ ...