Updating a JSON array by including a new key-value pair using Javascript

Below is a json string that needs to be converted into a new Json Array:

Raw Data:

[
    ["yrxqBHmPkNhZ60_eab97ebf-c2a3-40a5-972a-91597ad9a4ca_99371", "SUCCEEDED", "2023-08-31T21:59:31.325000+05:30", "2023-08-31T22:13:42.165000+05:30"],
    ["yrxqBHmPkNhZ60_f42702be-16c3-44bf-bc3b-6719c740a5e3_98405", "SUCCEEDED", "2023-08-31T21:43:25.581000+05:30", "2023-08-31T21:57:47.681000+05:30"],
    ["rk9QMf81WrT7DO_edd6e8de-9de4-4885-b970-9311443d81d5_98750", "SUCCEEDED", "2023-08-31T21:49:10.578000+05:30", "2023-08-31T21:56:20.197000+05:30"]
]

The following code snippet has been used to convert the above data into the expected format:

var dataObj = JSON.parse(myStr); // where myStr represents the data string above

var newData = new Array();

for(var i in dataObj) {  

 newData.push(dataObj[i]);

}

data.push(newData);

Expected Result:

[
    "type": "buffer",
    "data":[
    ["yrxqBHmPkNhZ60_eab97ebf-c2a3-40a5-972a-91597ad9a4ca_99371", "SUCCEEDED", "2023-08-31T21:59:31.325000+05:30", "2023-08-31T22:13:42.165000+05:30"],
    ["yrxqBHmPkNhZ60_f42702be-16c3-44bf-bc3b-6719c740a5e3_98405", "SUCCEEDED", "2023-08-31T21:43:25.581000+05:30", "2023-08-31T21:57:47.681000+05:30"],
    ["rk9QMf81WrT7DO_edd6e8de-9de4-4885-b970-9311443d81d5_98750", "SUCCEEDED", "2023-08-31T21:49:10.578000+05:30", "2023-08-31T21:56:20.197000+05:30"]
    ]
]

Answer №1

To achieve the desired outcome, follow these steps:

  1. Convert the JSON array into a Javascript array
  2. Construct a new object with type and actual data

const myStr = '[["yrxqBHmPkNhZ60_eab97ebf-c2a3-40a5-972a-91597ad9a4ca_99371","SUCCEEDED","2023-08-31T21:59:31.325000+05:30","2023-08-31T22:13:42.165000+05:30"],["yrxqBHmPkNhZ60_f42702be-16c3-44bf-bc3b-6719c740a5e3_98405","SUCCEEDED","2023-08-31T21:43:25.581000+05:30","2023-08-31T21:57:47.681000+05:30"],["rk9QMf81WrT7DO_edd6e8de-9de4-4885-b970-9311443d81d5_98750","SUCCEEDED","2023-08-31T21:49:10.578000+05:30","2023-08-31T21:56:20.197000+05:30"]]';

const jsonData = JSON.parse(myStr); // myStr contains JSON data as a string
const data = {
  type: "buffer",
  data: jsonData,
};

console.log(data);

Answer №2

Below is a functional demo:

let data = [
    ["yrxqBHmPkNhZ60_eab97ebf-c2a3-40a5-972a-91597ad9a4ca_99371", "SUCCEEDED", "2023-08-31T21:59:31.325000+05:30", "2023-08-31T22:13:42.165000+05:30"],
    ["yrxqBHmPkNhZ60_f42702be-16c3-44bf-bc3b-6719c740a5e3_98405", "SUCCEEDED", "2023-08-31T21:43:25.581000+05:30", "2023-08-31T21:57:47.681000+05:30"],
    ["rk9QMf81WrT7DO_edd6e8de-9de4-4885-b970-9311443d81d5_98750", "SUCCEEDED", "2023-08-31T21:49:10.578000+05:30", "2023-08-31T21:56:20.197000+05:30"]
]

console.log(Object.assign({type:"buffer"},{info : data}))

Answer №3

To store the JSON array directly without looping through it, you can simply assign it to the data field:

var dataArray = [
    ["yrxqBHmPkNhZ60_eab97ebf-c2a3-40a5-972a-91597ad9a4ca_99371", "SUCCEEDED", "2023-08-31T21:59:31.325000+05:30", "2023-08-31T22:13:42.165000+05:30"],
    ["yrxqBHmPkNhZ60_f42702be-16c3-44bf-bc3b-6719c740a5e3_98405", "SUCCEEDED", "2023-08-31T21:43:25.581000+05:30", "2023-08-31T21:57:47.681000+05:30"],
    ["rk9QMf81WrT7DO_edd6e8de-9de4-4885-b970-9311443d81d5_98750", "SUCCEEDED", "2023-08-31T21:49:10.578000+05:30", "2023-08-31T21:56:20.197000+05:30"]
];

var data = {type: 'buffer', data: []};

data.data = dataArray;

console.log(data);

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

Exploring Kotlin to retrieve information from Json fetch results

I am retrieving JSON data from this URL using OKhttp. My coding language of choice is Kotlin. { "CountryName": [{ "Country": "India", "CountryCode": "+91", "Population": "545121546846" }, { "country ": "Pakistan", ...

Can a JavaScript function be sent through a REST API using Node.js and Express?

I have a unique scenario where I need to send a custom JavaScript function as a response to a GET request made to an API endpoint. Currently, I am using Node.js with Express for my server implementation, but I am open to exploring other frameworks. When a ...

Tips for retrieving data from multiple text boxes in a loop in React js and transmitting it to an API

I am in the process of developing a quiz application where I aim to create multiple question input fields based on the administrator's inputs. For example, if the admin provides 10 questions for the quiz, I will then generate a form within a loop fo ...

Associating data with controller upon click event

My application displays a tab full of objects for the user to choose from by clicking on any line. Once they make their selection, I need to send specific data related to that object to the server. This is what the interface looks like: The tab is create ...

Is there a way to restrict a user to selecting just one checkbox in a bootstrap checkbox group?

I am having trouble implementing bootstrap checkboxes in my code. I want the user to be able to select only one checkbox at a time, with the others becoming unchecked automatically. Can someone please advise me on what I need to add to my code? Here is a ...

MUI Input component does not support the use of the oninput attribute

My MUI Input component is defined like this, but the oninput attribute doesn't seem to work in MUI: <Input variant="standard" size="small" type="number" inputProps={{ min: '0', o ...

EJS forEach method not displaying output

Trying to work with this .ejs file that's supposed to loop through an object and retrieve data from an API. However, after fetching the data, it appears that nothing is being displayed on the screen. I've checked the API results in the console l ...

I've been endeavoring to compare the content IDs from two APIs using Jmeter

I am faced with a challenge where I have two APIs that contain the same content but have different URLs. My goal is to compare all the contents from both APIs using jmeter. So far, I have utilized the json extractor by setting the path as $..contentid and ...

What is the best way to extract multiple variables from a function in JavaScript?

After creating the function buttonEffects() with four different button effects, I am now facing the challenge of bringing these variables outside of the function and using them in another function. Is it possible to achieve this without recoding everything ...

Incorporating Common Types for Multiple Uses

Is there a way to efficiently store and reuse typings for multiple React components that share the same props? Consider the following: before: import * as React from 'react'; interface AnotherButtonProps { disabled?: boolean; onClick: (ev ...

We are creating a table in JavaScript and mistakenly adding an unnecessary tbody

I am currently utilizing a combination of plain JavaScript and Jquery in order to dynamically generate a table. The issue arises when I attempt to use a for loop to iterate through the data obtained from an Ajax request, as it fails to create new rows. To ...

Showcase a sizable picture broken down into smaller sections

I am interested in creating a mapping application similar to Google Maps that can asynchronously load images from the backend. I am seeking guidance on where to begin and how to proceed in this endeavor. The ultimate goal is to have the image displayed w ...

Using jQuery to perform global search and replace with a variable

In this scenario, I am attempting to substitute every occurrence of the newname variable with a hyphen (-). However, in my specific case, newname is being interpreted as text instead of a variable. var newname = 'test'; var lastname = $(this).a ...

Having difficulty retrieving appropriate object from Json data

Using json with Selenium Ruby: @driver.find_element(:css, "#poi-tabs *[class='tab ']") This code works as expected. @driver.find_element(:css, JSON.parse(file)['xyz']['elemen']) However, the following code FAILS because th ...

AngularJS 2: Updating variable in parent component using Router

My current app.component looks like the following: import { Component, Input } from '@angular/core'; import {AuthTokenService} from './auth-token.service'; @Component({ selector: 'app-root', templateUrl: './app ...

Implementing global parameters in ui-router

Currently, I am utilizing ui-router in AngularJS as shown below: .state ('browse.category', { url: "/:category", templateUrl: "views/browseCategory.html", controller: function($stateParams, $scope) { $scope.params = $st ...

The server has denied access to the resource due to a HTTP 403 Forbidden error in the AJAX request

I have exhausted all resources online in an attempt to resolve an error I am encountering with my AJAX request. Even after trying XMLHttpRequest() request, the problem remains unsolved. Below is the code for my Ajax Request: $.ajax({ type: "POST", url: " ...

Troubleshooting: Issue with binding nested data property using bracket access in Vue3 v-model

Having an issue in Vue3 where I am unable to bind a nested property to v-model correctly. Check out the source code below: Template: <div id="app"> <span>{{level1.level2.level3}}</span> <br/> <span>{{level1[&ap ...

Steps for generating a unique division element for every javascript response

How can I dynamically create a new div for each response in JavaScript? The message is in JSON format containing all the messages sent and received. This is my JavaScript code: $.get("MessageServlet", function (responseJson) { $.each(responseJ ...

A mock or spy must be used for the jest function

I'm having an issue with the last expectation not being called in a test I'm writing to test the actions within my application. const pushData = jest.fn(() => Promise.resolve()); test('anotherAsyncCall is fired to get more info', ( ...