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

How to dynamically add HTML content to a JSON string with the help of Javascript

I am working with a JSON object that includes various messages to be displayed on a webpage using Javascript. This JSON file is located in a separate directory and I have full control over it, being loaded asynchronously. There are specific cases where di ...

Expanding the reach of the navigation bar

Hello Everyone, Is there a way to stretch my navigation bar so that the links are evenly spaced out across the browser window instead of being clustered together? I want it to be responsive rather than fixed in size. This is my HTML code: <div class= ...

Tips for inserting a row component into a table using Angular 7

I am currently using the latest version of Angular (7.2.0). I have created a custom tr component as follows: import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-table-row', templateUrl: './table- ...

Create unique error messages using Vue validators

Two fields named text and email are included in my template. Below is the structure of the template: HTML <!DOCTYPE html> <html> <head> <title>Vue - Validations</title> <script src="Libraries/vue/vue.min.js&qu ...

What is the best way to dynamically adjust the width of multiple divisions in Angular?

I am currently working on an angular project to create a sorting visualizer. My goal is to generate a visual representation of an array consisting of random numbers displayed as bars using divisions. Each bar's width will correspond to the value of th ...

Changing the color of HTML text based on a variable in Vue JS can be achieved by altering the CSS styles dynamically

I have developed a website that shows values with a set threshold. I now want to change the color of the values when they exceed the threshold, but I am unsure of how to proceed. I want to display consultation.indicateurs.TRS in red when it exceeds the va ...

Tips for organizing JSON data from Google Maps' Direction Service for storage in a MongoDB database and displaying it on a map

Utilizing the Google Maps Directions service for navigation, I aim to preserve the response in MongoDB in JSON format. This will allow me to easily plot the route on the map again. How should I structure the JSON data for the routes array retrieved from th ...

Attempting to display JSON data retrieved from a decoded base64 string in Python

After attempting to decode a value using base64, my goal is to use the decoded strings individually. Here is an example of my decoded base64 data: { "trailerColor": "FF0017", "complete": 59, "bounds": [ 25, 65, 62, 5 ], "Stamina" ...

The video in the TypeScript code within the Owl Carousel is not displaying properly - only the sound is playing. The video screen remains stationary

I recently updated my query. I am facing an issue while trying to play a video in Owl Carousal with a button click. The video plays sporadically, and most of the time it doesn't work properly. When playing without the carousel, a single video works fi ...

Problem: Values are not being posted with AJAX when using $(form).serialize()

I'm encountering an issue with submitting a form using AJAX. I initially tried to pass the data using $("#myForm").serialize(), but for some reason, the receiving page doesn't receive the data. Take a look at my form: <form id="myForm"> ...

Struggling to deserialize the JSON data into a list of objects

Consider the provided JSON data stored in a file named database.json at the project's root: { "customers": [{ "id": 1, "name": "Bob" }, { "id": 2, "name": &q ...

Best practice for sending a PDF file in JSON format with Node.js

Our team is currently in the process of building a Node.js API with Express.js. One specific function within our project involves receiving an ID and returning a pdf file from AWS in a json response format like this: { ID: "id10", pdf: [ ...

Restrict the Angular ng-repeat directive to specific rows only

Suppose we have a JSON dataset listing all languages of books: $scope.data = [{ "title": "Alice in wonderland", "author": "Lewis Carroll", "lang": ["en"] }, { "title": "Journey to the West", "author": "Wu Cheng'en", "lang": [" ...

What is the best way to filter out a specific item from an arrayList in a JSON response using

In my demo json response, I want to display all the data from "CategoryList" except for the list where "CategoryName": "NEW ARRIVALS". Is there a way to filter out specific data from my Json response by using the keyword "New"? If the keyword "New" appear ...

Is it permissible to make alterations to npm modules for node.js and then share them publicly?

I have made modifications to a module called scribe.js that I use in my own module, which is published on npm. Instead of using the original module as a dependency for my module, I would like to include my modified version. I am unsure about the legal impl ...

Combining the first name, last name, and code in Javascript

I'm attempting to combine the initial letter of both names with the randomly generated code. var firstname = prompt("Please input your first name."); var lastname = prompt ("Please input your last name."); if (amountCorrect >= 4){ ...

Using JSON data with PHP, MySQL, and jQuery

I'm encountering an unusual issue. Whenever I try to access my JSON code with the corresponding numbers [0], [1], etc., I only get the first character of the object. Here's a snippet of my code: test2.php if(isset($_POST['getCustomersArr ...

Ways to reset the input field of Material UI

I'm encountering an issue with clearing a form that I created using Material UI. Despite searching for solutions on Stackoverflow, none of them seem to work for me. Using setState did not achieve the desired result of clearing the form. I am looking ...

Differences between throwing errors, returning error objects, and using callbacks in Javascript

Currently, I am developing an assembler and simulator for a simplistic assembly language that my computer science students use during their classes. The project is being written in JavaScript with the intention of creating a user-friendly interface in the ...

Issues occurring with setting the variable using the Google latlng API

I've tried searching for solutions on various forums, including stackoverflow, but haven't been able to make it work. The issue lies in this code snippet where the variable 'pos' is not being set: var geocoder= new google.maps.Geocoder ...