transforming JSON key names by associating them with their corresponding JSON values and modifying the key names

My challenge lies in converting a JSON string from one format to another. The initial format is:

[
  {
   clientIDs:
         "WELL #6",
   analyteIDs:
         [
          "7440-62-2",
          "7440-28-0"
         ]
  }
]

The desired output should look like this:

[
  {
   header:
         "WELL #6",
   items:
         [
          header: "7440-62-2",
          header: "7440-28-0"
         ]
  }
]

I am facing difficulty with the values that do not have key names specified.

Answer №1

It's unfortunate that JavaScript doesn't have built-in support for key value arrays, but you can work around it by using objects to store keys and values instead. Here's how you can achieve a similar result:

[
  {
   header:
         "WELL #6",
   items:
         [
          { header: "7440-62-2" },
          { header: "7440-28-0" }
         ]
  }
]

Here are the steps you'll need to follow:

  • Start with an array of objects.
  • Assume that the keys you want to modify will always be present in the objects.

 const myObjects = [
      {
       clientIDs:
             "WELL #6",
       analyteIDs:
             [
              "7440-62-2",
              "7440-28-0"
             ]
      }
    ]

    myObjects.map((myObj) => {
      myObj['header'] = myObj.clientIDs;
      myObj['items'] = myObj.analyteIDs.map((item) => {
        return { header: item }
      });
      
      // Note: This approach may fail if keys are dynamic or missing in some objects
      delete myObj['clientIDs'];
      delete myObj['analyteIDs'];
    });

    console.log(myObjects);

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

Inquiring about browserify or webpack on a website using node - a few queries to consider

Seeking assistance with a website project I am currently working on. The project consists of 7 HTML documents, 3 stylesheets, 8 JavaScript files (including jQuery.min.js and some additional jQuery plugins), and various images. I am looking to bundle and mi ...

Switching a Rails/Ajax form from create to update mode upon submission

While experimenting with a star ratings page, I encountered an issue where the form element remained in "Create" mode instead of updating to an "Update" method after submission. The rating form is ajaxified, but it lacks the functionality to dynamically sw ...

What is the best approach to execute a javascript on an HTML page that is dynamically generated?

Working with jQuery Mobile, I have a situation where I am creating a listView of pages based on events stored in a database. Each event is parsed on my webpage to generate a unique HTML page for each one. Within each page, I include a distinct "subscribe" ...

The performance of Three.js Transform Controls is hindered by lag

After adding transform controls to a sphere in my scene to enable movement, I also included orbit controls for panning around. Initially, everything worked smoothly without any lag. However, once I started moving the sphere, significant lag became apparent ...

Simple integration of JSP, JSON, and AJAX

I need help testing a simple login functionality using AJAX. Here's the code snippet: <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Login Test Page</title> <script src="../js/j ...

The JSON File data is not appearing on the screen in React Native due to a local data issue

Exploring RN and currently navigating through displaying dynamic data from a locally created JSON file. My goal is to show a list of characters where users can click on a character's button to access their profile screen. However, I encounter an error ...

A common parser that outputs a hash-map instead of a Plain Old Java Object (

Here is the initial code snippet (A): JsonFileHandler<Device> jsonFileHandlerDevice; final List<Device> devicesList = jsonFileHandlerDevice.getList(); And this is the class used in code snippet (A): class JsonFileHandler<T>: @Override ...

What is the method for combining two SC.RecordArray instances in Sproutcore?

Below is the code snippet : queryTree = SC.Query.local('Tree.Category', "categoryId = {categoryId}", { categoryId: this.get('guid'), orderBy: "name ASC" }); queryNote = SC.Query.l ...

Directive Template with Dynamic Fields (AngularJS)

I am interested in creating a custom directive that can bind to any object, allowing me to specify the field used in the template for display. Previously, I was limited to using {{item.Name}}, but now I want the flexibility to define the display field. Cu ...

Searching and editing JSON objects using C#

Is it possible to search for and change specific values within a Json string without the need for serialization and deserialization? ...

AngularJS is causing the D3.js Bubble chart graph to not display properly

I've been attempting to enhance my Bubble chart graph created with D3.js by incorporating AngularJS, but I'm facing some difficulties. Despite going through this tutorial, nothing seems to be working as expected. Below is the code I have written ...

Changing the Direction of News Ticker Movement from Right to Left

I need to switch the news ticker movement direction from right to left to left to right because I will be using Arabic language, so it is crucial to change the movement direction. Despite trying for several days, I have been unable to find a solution. HTM ...

The key length specified in crypto.createCipheriv is not valid

After utilizing NodeJS v8.11.0, I managed to create a base64-encoded key with the following code: const secret = 'shezhuansauce'; const key = crypto.createHash('sha256').update(String(secret)).digest('base64'); //output is RE ...

The code I copied from a tutorial continually presents me with syntax errors

After following a tutorial on YouTube and copying the code exactly, I encountered two errors when running it. The errors were: ';' expected and ',' expected. Here is the link to the original tutorial for reference: https://youtu.be/IgAH ...

What is the best way to locate elements with the term "download" in them using Selenium's x-path feature?

I'm currently utilizing Selenium for web scraping purposes and I am in need of a way to identify all clickable elements that contain the word "download" (regardless of capitalization) within their link text, button text, element ID, element class, or ...

What is the best way to update a nested property in an object?

Consider the following object: myObject{ name: '...', label: '...', menuSettings: { rightAlignment: true, colours: [...], }, } I want to change the value of rightAlignment to fals ...

How can I troubleshoot jQuery not functioning in iOS even though it works on Safari?

Trying to implement jQuery on a website using xCode simulator for testing, but experiencing issues. Works fine on Safari webkit though. Click here to view the site. I would appreciate finding out what's causing the problem, as well as advice on how t ...

The Jquery script is ineffective for newly added elements

After creating an Ajax Form that functions well, I noticed that when the result of the form is another form, my script does not work for the new form generated. Is there a way to make the new form function like the old one? $(document).ready(function() ...

What steps can I take to hide my textarea after it has been clicked on?

Recently, I reached out for help on how to make my img clickable to display a textarea upon clicking. While I received the solution I needed, I now face a new challenge - figuring out how to make the textarea disappear when I click the img again. Each clic ...

Is it possible to invoke a computed property within the props of a child component in Vue.js?

In the context of my child and parent components, I have a boolean prop in the child component with a default value of false. When calling the child component within the parent component and setting it based on a computed function that returns a boolean va ...