Manipulating Keys in JavaScript Arrays of Objects dynamically

I am facing a challenge where I need to switch keys with values within an array of objects

var myArray = [
               {'a' : {'x': ['Bob', 'Rob', 'Mike'], 'y': [4,5,6], 'name': 'a'}}, 
               {'b' : {'x': ['Kris', 'Elen', 'Hanna'], 'y': [10,11,12], 'name': 'b'}} 
]

The desired outcome is to swap the values of x and y in each object:

var myNewArray = [
    {'a' : {'x': [4,5,6], 'y': ['Bob', 'Rob', 'Mike'], 'name': 'a'}}, 
    {'b' : {'x': [10,11,12], 'y': ['Kris', 'Elen', 'Hanna'], 'name': 'b'}} 
]

I attempted to iterate through the array and create a new one, but encountered an error message: Uncaught TypeError: Cannot read property 'name' of undefined

var test = [];

for (var i = 0; i < Object.keys(myArray).length; ++i) {
    test['trace' + (i+1)] = {
                            name: myArray[i].name, 
                            x: myArray[i].y, 
                            y: myArray[i].x
    };
}

I am seeking a dynamic solution as manually changing them is not feasible

Answer №1

To reverse the values of two keys and apply the transformation to all objects in an array, you can utilize the Array#map method as shown below:

const myArray = [{ 'a': {'x': ['Bob', 'Rob', 'Mike'], 'y': [4, 5, 6],'name': 'a' }},{'b': {'x': ['Kris', 'Elen', 'Hanna'],'y': [10, 11, 12],'name': 'b'}}];

const switchKey = (obj, key1, key2) => {
  const {[key1]: a, [key2]: b} = obj;
  //reverse values here
  return {...obj, [key1]: b, [key2]: a}
}

const switched = myArray.map(o => {
  let [key, value] = Object.entries(o)[0];
  return {[key] : switchKey(value, "x", "y")};
});
console.log(switched);

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

Retrieving Axios error codes within an interceptor

How can error codes like ERR_CONNECTION_REFUSED (indicating the API server is down) and ERR_INTERNET_DISCONNECTED (indicating the local network is down) be accessed when using response interceptors with axios in client-side JavaScript, React, etc.? While ...

What is the best way to utilize both doPost() and doGet() requests in a single servlet while incorporating ajax technology?

Currently working on a small project involving JSP servlets. I need a practical example demonstrating the implementation of both the doGet() and doPost() methods within the same servlet, while handling AJAX calls within a JSP form. Additionally, could you ...

Show the value of an array index in JavaScript

Imagine retrieving data from a local API using the code snippet below: {console.log("Bin", this.state.rows.filter(qc => qc.BinsByDayByOrchardsQCs.length > 0).map((bin) => bin))} The output you get may look something like this: 0: {…} ...

Using Javascript to pass the value of a selected checkbox

I am having an issue with passing a row value to a different function when a user clicks on a checkbox in the last column of a table. The code I have written doesn't seem to be firing as expected. Can anyone help me figure out what might be missing in ...

The issue with Three.js responsive canvas is that it fails to properly adjust the size of the

I'm currently working on a threejs basic scene and attempting to create a responsive canvas for a full-screen experience. However, the mesh inside the scene is not resizing correctly as expected. Instead of remaining a cube, it distorts into a rectang ...

Modifying the data of a particular object in my rtk asynchronous thunk

I recently started using rtk and immer. I encountered an issue when trying to update my state with redux. For example, when a user logs in, I store their data in redux with the following structure: data = { "user_profile" : { "name&q ...

Changing view upon button click in ReactJS: implement conditional rendering

After grasping the fundamentals of ReactJS, I am eager to put my knowledge into practice by building a small application. The application includes two images below. In the Home view (1st image), there are several buttons that, when clicked, should lead to ...

Guide on leveraging event delegation to trigger a function depending on the id of the clicked element

Although I have experience with event delegation, I am currently facing a challenge in setting up a single event listener that can execute one of three functions based on the ID of the element clicked. Here is the existing code without event delegation: ...

The Bootstrap navigation menu is functioning properly when opening, but has an issue when attempting

Creating a mirrored version of an HTML file using NuxtJS, I've included the following code snippet in the Navbar component for my NuxtJS project. <template> <section id="navigation-menu" class="menu menu3 cid-sLhoPz7Ycg" ...

What is the preferred method for storing JSON data - using a single data attribute or multiple separate data attributes?

When it comes to storing multiple data attributes for a single DOM element, the question arises: Is it better to have a single data attribute containing JSON data, or is it more efficient to have separate data attributes for each value needed? <select ...

Strip away characters from a JSON object

Attempting to parse JSON using Logstash has presented a challenge due to the structure of the file I am working with. The simplified format of the file is as follows: -4: {"audit":{"key1":"value1","key2":"value2"}} -4: {"audit":{"key1":"value1","key2":"va ...

Insert elements to an XML document in Node.js using libxmljs

I've been working on updating an XML file by adding a new child node using the code below: var libxml = require('libxmljs'); var xml = '<?xml version="1.0" encoding="UTF-8"?>' + '<root>' + ...

Generate a high-resolution image using PhaserJS

I've been experimenting with creating graphics using PhaserJS and now I'm looking for a way to export them as high-resolution images or, even better, as vector-based graphics. Here's an example of the code I've been working on: var con ...

Securing client side routes in Vue.js: Best practices

Currently, I am in the process of developing a spa using Vue.js as the front end framework. It interacts with a back-end system that utilizes pure JSON and jsonwebtokens for security. While I am more experienced with the React ecosystem, my new role requir ...

Exploring numerous choices within a multi-select "category" search bar (web scraping)

Looking to scrape data from this French website using Python and the bs4 library: the content is in french :) . Specifically interested in extracting all possible values of a multi-select search bar named 'TYPE DE BIENS'. This type of search bar ...

Two separate tables displaying unique AJAX JSON response datasets

As a beginner in javascript, I am facing a challenge. I want to fetch JSON responses from 2 separate AJAX requests and create 2 different tables. Currently, I have successfully achieved this for one JSON response and table. In my HTML, I have the followi ...

Converting an array of object values to an Interface type in Typescript

In my JSON document, I have an array named dealers that consists of various dealer objects like the examples below: "dealers" : [ { "name" : "BMW Dealer", "country" : "Belgium", "code" : "123" }, { "name" : ...

Emphasizing the content of the text file with the inclusion of span tags

I am relatively new to working with angular js and javascript. I have a document or text file that looks something like this: Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dumm ...

Customize Input Values by Selecting an Option with jQuery-UI Autocomplete

Hello there, I am a newcomer to java-script and could really use some help. My goal is to have the data in the country field automatically populated when a user enters data into the city field. I have an xml file: <ROWSET> <ROW> <city>&l ...

Issue with Next JS router.push not functioning unless the page is refreshed

I'm currently running Next.js 14.2 in my project with the page directory structure. After building and starting the application using npm start, a landing page is displayed with a login button that utilizes the <Link> component. I have also disa ...