Modify the key within an array of objects that share a common key

I have an object structured as follows:

NewObjName: Object { OLDCOLUMNNAME1: "NEWCOLUMN_NAME1", OLDCOLUMNNAME2: "NEWCOLUMN_NAME2", OLDCOLUMNNAME3: "NEWCOLUMN_NAME3"}

Next, there is an array containing objects in this format:

array: [
1: Object { OLDCOLUMNNAME1: "VALUE", OLDCOLUMNNAME2: "VALUE", OLDCOLUMNNAME3: "VALUE"}
2: Object { OLDCOLUMNNAME1: "VALUE", OLDCOLUMNNAME2: "VALUE", OLDCOLUMNNAME3: "VALUE"}
3: Object { OLDCOLUMNNAME1: "VALUE", OLDCOLUMNNAME2: "VALUE", OLDCOLUMNNAME3: "VALUE"}
]

Both objects share a common key = OLDCOLUMNNAME.

The goal is to change the key (OLDCOLUMNNAME) to NEWCOLUMN_NAME from the first object (NewObjName).

The desired output should be:

array: [
1: Object { NEWCOLUMN_NAME1: "VALUE", NEWCOLUMN_NAME2: "VALUE", NEWCOLUMN_NAME3: "VALUE"}
2: Object { NEWCOLUMN_NAME1: "VALUE", NEWCOLUMN_NAME2: "VALUE", NEWCOLUMN_NAME3: "VALUE"}
3: Object { NEWCOLUMN_NAME1: "VALUE", NEWCOLUMN_NAME2: "VALUE", NEWCOLUMN_NAME3: "VALUE"}
]

An attempt was made using the following code:

const transformed = array.map(x => {
            // console.log(x); // loop through array with objects
            Object.keys(x).map(key1 => {
            // console.log(key1); // get OLDCOLUMNNAME

                Object.keys(NewObjName).map(key => {
                // console.log(key); // get OLDCOLUMNNAME from NewObjName
                // console.log(NewObjName[key]) //  NEWCOLUMN_NAME

                if (key1 === key) {
                   //if true i just try to set into OLDCOLUMNNAME to NEWCOLUMN_NAME
                   key1 = NewObjName[key]
                   delete NewObjName[key]
                }
         })
    })
})

However, when checking the result (console.log(transformed)), it returns undefined.

Answer №1

If you are looking to transform an object, utilizing the reduce and forEach methods can be quite beneficial.

const modifiedObj = array.reduce((accumulator, current) => {
  const newObj = {}
  Object.entries(current).forEach(([key, value]) => { // access each item 
    newObj[newKeyName[key]] = value;                 // map the key using newKeyName lookup table
  })
  accumulator.push(newObj)
  return accumulator;
}, [])
console.log(modifiedObj)
<script>
const newKeyName = {
  OLDKEY1: "NEW_KEY1",
  OLDKEY2: "NEW_KEY2",
  OLDKEY3: "NEW_KEY3"
}

const array = [{
    OLDKEY1: "VALUE1",
    OLDKEY2: "VALUE2",
    OLDKEY3: "VALUE3"
  },
  {
    OLDKEY1: "VALUE11",
    OLDKEY2: "VALUE22",
    OLDKEY3: "VALUE33"
  },
  {
    OLDKEY1: "VALUE111",
    OLDKEY2: "VALUE222",
    OLDKEY3: "VALUE333"
  }
]
</script>

Answer №2

One way to approach this issue would be with a general solution like so:

const data = [
    { OLDKEY1: 'VALUE', OLDKEY2: 'VALUE', OLDKEY3: 'VALUE' },
    { OLDKEY1: 'VALUE', OLDKEY2: 'VALUE', OLDKEY3: 'VALUE' },
    { OLDKEY1: 'VALUE', OLDKEY2: 'VALUE', OLDKEY3: 'VALUE' },
  ];
  
// specifying the mapping of old keys to new keys
  const mapKeys = {
    OLDKEY1: 'NEWKEY1',
    OLDKEY2: 'NEWKEY2',
    OLDKEY3: 'NEWKEY3'
  };
  
// function to replace old keys with new keys according to the map
const replaceOldKeys = (obj, keyMap) => Object.keys(obj)
    .reduce((result, currentKey) => Object.assign(result, { [keyMap[currentKey]]: obj[currentKey] }), {});
  
// looping through the data array and applying key replacement using the above function
const newData = data.map(item => replaceOldKeys(item, mapKeys));

console.log(newData)

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

Maintain the structure of ajax POST requests and display a real-time feed of

I've been developing an openvz script to run virtual machines at home. I've been exploring JavaScript and AJAX functions to send post requests, which are then displayed in the innerHTML section of my webpage. However, I've encountered an iss ...

AngularJS function orderBy reverses the array instead of sorting it

I encountered an issue where, after clicking the 'order button', the table does not order as expected. Instead, it reverses all the td elements. For example, 'A', 'C', 'B' becomes 'B', 'C', "A". I ...

Using Typescript: accessing all properties from a specified type while excluding one

Currently working in React, I am interested in extending my type from another, with the exception of some props. This is how I want to approach it : import React from 'react'; import { withTheme } from 'styled-components'; import SvgBa ...

Solution: "The Mongoose Model.find method consistently provides an empty result set."

Currently, I am utilizing mongoose in combination with next.js to interact with an existing collection. Despite the collection not being empty, the mongoose model.find() function consistently returns an empty array. Below is my model code: const mongoose ...

Tips for concealing JavaScript files from the Chrome Developer Tools while using Next.js

Currently working on a project using Next.js. I've noticed that the utils/components are quite visible through the Chrome Developer Tools, as shown in this image: https://i.sstatic.net/jaLmg.png Is there a way to hide them from being easily accessib ...

Issue: The `libsass` component could not be located

When attempting to run an Express app using node-sass-middleware on Ubuntu, I encountered this error: 0 info it worked if it ends with ok 1 verbose cli [ '/home/mohamed/.nvm/versions/node/v0.12.7/bin/node', 1 verbose cli '/home/mohamed/.n ...

Problem encountered with the JavaScript for loop failing to execute consistently on each iteration

Currently, I am working on a JavaScript code that alerts the count in an array of pages. The variable urls represents an array of page names, while count contains the count value. My goal is to alert the count value for each page in the urls array. Howe ...

Issue encountered: Next.js has failed to hydrate properly due to a discrepancy between the initial UI and server-rendered content

Uncertain about the cause of this error? The error seems to disappear when I remove the provided code segment. What is triggering this error in the code snippet and how can it be fixed? <div className="relative flex flex-col items-center pt-[85.2 ...

Adaptable images - Adjusting image size for various screen dimensions

Currently, my website is built using the framework . I am looking for a solution to make images resize based on different screen sizes, such as iPhones. Can anyone suggest the simplest way to achieve this? I have done some research online but there are t ...

JavaScript implementation of a carousel slider with responsive design

I have successfully implemented a feature carousel slider using the jquery.featured.carousel.js file along with some CSS. Here is the jsfiddle link to my project: LINK. When running this code on localhost, I noticed that I need to refresh the page every ...

Can you provide a succinct explanation of what constitutes a well-defined "landing page"?

Could someone provide a clear and concise explanation of what exactly constitutes a landing page and how it should be utilized? I'm struggling to grasp the concept. Where is the optimal placement for a landing page on a website? Is it best placed o ...

Upon hitting submit, the form remains unresponsive

I have been developing a permissions system for my NodeJS project (Using the SailsJS MVC) and encountered an issue. After resolving my initial error as detailed here, I am now facing a problem where the form is unresponsive. It neither shows an error in th ...

Returning to the previous page

Having some trouble navigating back to the previous page. When I click the cancel button, it runs a function that uses history.back();, which works correctly. However, there is a validation on the page, so it checks all fields before navigating back. I&ap ...

Webpack loaders or plugins: understanding the distinction

Can you explain the distinction between loaders and plugins in webpack? I found on the documentation for plugins that it states: Plugins are used to incorporate extra functionalities usually related to bundles within webpack. While I understand that b ...

Hold off on progressing until the http.get request in Angular 4 has completed

Currently, I am in the process of creating a new registration form for an app using Ionic and utilizing ASP.Net(C#) for my API. My objective is to validate if a user already exists when the input blur event is triggered. However, I'm encountering an ...

What is the best approach to managing a Symfony form that contains TWO CollectionType child forms?

I have been referring to the Symfony guide here which explains how to generate and save a collection of associated entities within a form. Following the example provided in the guide, I have successfully implemented the functionality for adding and removi ...

Prevent multiple requests on jQuery infinite scrolling

I have implemented pagination on my website where the next page is loaded automatically when the user reaches the bottom of the page. This is achieved by using jQuery's .on('scroll', this.detectScroll()) method which triggers a function to l ...

"Exploring the possibilities of Ajax in conjunction with Sol

I recently completed a tutorial on Ajax Solr and followed the instructions in step one. Below is the code I wrote: header.php: <script type="text/javascript" src="static/js/ajax-solr/core/Core.js"></script> <script type="text/javascript" s ...

Angular: Showing the Gap between Basic Elements within an Array in the Template

I've been working on displaying a nested JSON object in a table, where there is an array of strings like obj.someKey = ['a','b','c']. Currently, I am directly showing the array content in the td tag of the table. <td ...

Using the `forEach` method nested within another `forEach

I'm facing an issue with the useEffect hook where it seems to not be rendering correctly. My cardArticle is only concatenating the last array and that's it. Below is the code snippet: const [articles, setArticles] = useState([]); const [cardA ...