Updating the key within an array of objects

In my array of objects, I have the following data:

arrayOfObject = [{'key1': [1,2]} , {'key2': [1,2,3]} , {'key3': [1,2,4]}]

I know the name of the key that I want to replace in my array :

var keyString = 'key1';

And I also have the new name that this key should be changed to:

var newKey    = 'newKey'

My goal is to transform my array into this format:

arrayOfObject = [{'newKey': [1,2]} , {'key2': [1,2,3]} , {'key3': [1,2,4]}]

To achieve this, I found a helpful resource on JavaScript Object Key Renaming, but I am unsure how to access the object that contains the initial key 'key1' in the array.

Please note that the keyString value will be different each time. Therefore, simply using arrayOfObject[0] won't solve the problem.

Here is the link to the working example on JSFiddle: https://jsfiddle.net/tcatsx6e/

Answer №1

Here is a potential solution to the problem:

const arrayOfObjects = [{'key1': [1,2]} , {'key2': [1,2,3]} , {'key3': [1,2,4]}];

const keyToFind = 'key1';
const newKeyToAdd = 'newKey';

const updatedArray = arrayOfObjects.map(function(obj) {
  if (keyToFind in obj) {
    let value = obj[keyToFind];
    delete obj[keyToFind];
    obj[newKeyToAdd] = value;
  }
});

You can also view a complete example by visiting this jsbin link.

Answer №2

This function is designed to find the index of the specific object that needs to be modified.

function getIndex(arr, keyString) {
  for (var i = 0; i < arr.length; ++i) {
    if (arr[i][keyString] !== undefined) {
      return i;
    }
  }
}

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

Removing elements from an array of objects using specific values stored in another array - JavaScript

I'm currently working on implementing a reducer in redux that can delete multiple items from the state based on an array of values. Let's say I have the following array: const idArray = ["935", "933", "930"]; My goal is to remove objects that ...

Performing an API GET request in a header.ejs file using Node.js

Looking to fetch data from an endpoint for a header.ejs file that will be displayed on all routed files ("/", "/news" "/dogs"). Below is my app.js code: // GET API REQUEST var url = 'https://url.tld/api/'; request(url, function (error, response, ...

Building a matrix-esque table using d3.js reminiscent of HTML tables

I would like to generate a table resembling a matrix without numerical values. 1. Here is an example of my database table: | CODE | STIL | SUBSTIL | PRODUS | |------|-------|----------|---------| | R | stil1 | substil1 | produs1 | | R | stil1 | s ...

Designing a MongoDB document structure that includes subdocuments with similar properties

Currently, I am in the process of developing a referral feature and I am relatively new to MongoDB. My main issue lies in figuring out how to construct a document that contains multiple similar subdocuments - specifically, 4 email addresses. The challenge ...

What is the best way to determine the frequency of each element in a two-dimensional array that has been read from a file?

Having trouble with the Array.count method on a two-dimensional array. I'm loading my two-dimensional array from a file that was previously stored, something like this: [[1, 1, 1, 1, 1, 2, 2, 1, 1, 1], [1, 1, 1, 1, 1, 2, 2, 1, 1, 1], [1, 1, 1, 1, 1, ...

Exploring ng-view navigation in AngularJS

I have come across an SEO issue while working on a static website in AngularJS. Google Webmasters Tools report no crawl errors, but when I attempt to fetch different routes, it consistently returns the same home page result. It seems to be ignoring what ...

The xslt code is failing to invoke the JavaScript function

I am currently utilizing xslt for the transformation of xml to html. Below is an example of an .xml file. <ImportOrganizationUtility-logging> <log-session module-name="ImportOrganizationUtility" end="17:54:06" start="17 ...

My global variable keeps getting caught by the addEventListener function

My script does not use jQuery and has an addEventListener on a button click. The issue is that after the first run, I want to change the value of "sendingurl" to something else. However, even though sendingurl is updated with the new id value, it doesn&apo ...

Is there a way to simultaneously modify several data variables within a Chart.js label?

I'm currently working on dynamically updating a line chart with two data entry points using the variable name "data." Take a look at the code snippet below: var lion = new Chart(ctx2, { type: "line", data: { labels: ["Apr", "May", ...

Trigger a drop-down list in React when typing a specific character, like {{ or @, in an input field

Is there a way in React.js to display a list or dropdown when a user types a certain character like '@' or '{{ }}' in the input text area? The user should be able to select an option from this list and have it inserted into the text are ...

Adding external JSON data to a plain HTML document can be achieved through the process of

I have been experimenting with extracting data from an API in JSON format, but I am struggling to figure out how to convert the JSON tags into HTML elements. You can view a sample of the JSON data here. Does anyone know how to transform this JSON into DI ...

What is the best way to transfer an array from .Net to C?

Utilizing an open-source library written in C, I am attempting to wrap it and expose it to .Net. My expertise lies more in F# than in C. Up to this point, I have successfully called the demo code from F#, adapting the C code to accept an integer parameter ...

My goal is to utilize React JS to generate a table by sending the values through props using an array of objects

I have experience building tables as part of various projects, but I am facing challenges creating a table based on the provided format for this specific project. My goal is to utilize the RecordTable Component, render the table component, pass the row com ...

What is the best method for transmitting additional information to an API?

Hey everyone, I'm currently struggling to send the shipping address to api/checkout. I attempted to send the body as an object with the cart details and shipping address as object properties, but that approach didn't yield any results. Is there a ...

How can I access the marker's on-screen location in react-native-maps?

Looking to create a unique custom tooltip with a semi-transparent background that can overlay a map. The process involves drawing the MapView first, then upon pressing a marker on top of the MapView, an overlay with a background color of "#00000033" is dra ...

Implementing 'Load more...' in Rails for infinite scrolling instead of traditional pagination

I currently have a collection of items and have been utilizing the will_paginate gem. However, I am interested in implementing a "load more..." feature at the end of the list. Is there a straightforward way to achieve this with will_paginate, or should I e ...

How to Convert Irregular Timestamps in Node.js?

Currently, I am utilizing an API to retrieve information from Google News and proceed to save the data in Firestore. The challenge lies in the fact that the API delivers timestamps in various formats which are not uniform. For example: "1 Day Ago", "June ...

I don't understand why this error keeps popping up. It seems that there are several `InputBase` components nested within a

Issue: The error message indicates that there are multiple instances of the InputBase component within a FormControl, causing visual inconsistencies. Only one InputBase should be used. I have tried enclosing my forms within the FormControl, but the error ...

Utilizing the Filter Function to Eliminate an Element from an Array

I am a beginner in the world of React and I'm currently working on developing a simple timesheet tool where users can add tasks and save them. My tech stack includes React and Typescript. Currently, my main component has an empty array for tasks and ...

Random crashes are observed in Selenium tests during the execution of JavaScript code

Currently, I am in the process of writing functional tests for a Zend application. These tests are executed using PHPUnit and a wrapper called https://github.com/chibimagic/WebDriver-PHP In order to handle the extensive use of JavaScript and AJAX in the a ...