JSON object containing nested arrays in JavaScript

In my current setup, I am utilizing a nested array with the following organization:

arr[0]["id"] = "example0";
arr[0]["name"] = "name0";
arr[1]["id"] = "example1";
arr[1]["name"] = "name1";
arr[2]["id"] = "example2";
arr[2]["name"] = "name2";

My goal now is to extract a nested JSON Object from this array

arr{
 {
 id: example0,
 name: name00,
 },
{
 id: example1,
 name: name01,
 },
{
 id: example2,
 name: name02,
 }
}

I had initially attempted to achieve this with JSON.stringify(arr);, however, it proved to be unsuccessful. If anybody has a solution, please share as I would greatly appreciate it.

Thank you!

Answer №1

If you're working with an array structured like this, where each subarray's initial item represents the ID and the second item represents the name:

const array = [["example0", "name00"], ["example1", "name01"], ["example2", "name02"]]

The first step is to transform it into an array of objects.

const arrayOfObjects = array.map((el) => ({
  id: el[0],
  name: el[1]
}))

After that, you can use JSON.stringify(arrayOfObjects) to obtain the JSON formatted data.

Answer №2

To ensure a successful array creation:

dataArr = [
 {
 code: 'sample0',
 title: 'title00',
 },
{
 code: 'sample1',
 title: 'title01',
 },
{
 code: 'sample2',
 title: 'title02',
 }
];

console.log(JSON.stringify(dataArr));

It is important to note that the array is being stored in a variable. Additionally, square brackets [] are used for creating arrays instead of curly braces {}.

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

Maxima's nested for loops generate arrays efficiently

With the goal of creating 11 arrays in Maxima, I attempted the following approach: for n:1 step 1 while n<=11 do( for j:1 while j<=21 do( if i<j then aa[n][i,j]:i+j+n)); Although this compiles without errors, I am unable to use it as intended. F ...

Serializing MongoDB, JSON objects, and dictionary members

Imagine having a class structured like this: class A { Dictionary<string, string> Dict1 { get; set } } Now, when serializing it to Json, you want the output to be: "A" : {"strKey1" : "strVal1", "strKey2" : "strVal2"} instead of: "A" : { "Dict ...

Build a new shop using a section of data from a JSON database

Let's say I have a JSON store that is set up as shown below var subAccountStore = new Ext.data.JsonStore({ autoLoad: true, proxy: { type:'ajax', url : '/opUI/json/subaccount.action?name="ABC"' }, fields: ['acc ...

Retrieving child class prototype from superclass

In my current project, I am working on implementing a base class method that shares the same logic across all child classes. However, I need this method to utilize specific variables from each child class. function A() {} A.prototype.foo = 'bar' ...

The JSON retrieved from the API contains additional characters

Currently, I am dealing with an API that is quite old and unfortunately lacks sufficient documentation. Upon making a GET request on a specific route, the response returns JSON data along with additional characters at the beginning. This unexpected sequen ...

javascript if condition not executing properly

I am struggling with my random number generator that should generate numbers between 5 and 15. I am trying to change the position of the 'chest' div based on the number generated by the computer, but for some reason it is not working as expected. ...

What is the process for deleting an attribute from the RequestSpecification/FilterableRequestSpecification body?

Hey there, I've been working on a simple method that takes a String argument as a path or "pointer" to attributes in JSON, and this method is meant to remove those specified attributes. The challenge I'm facing is that while I can retrieve the ...

Create a new cookie in Angular if it is not already present

I am looking to check if a cookie is set in Angular. If the cookie is not found, I want to create a new one. Currently, I have this code snippet: if ($cookies.get('storedLCookie').length !== 0) { $cookies.put('storedLCookie',' ...

Add some texture to one side of the quadrilateral

I have a project in threejs where I need to display an image of a cat within a rectangle. The challenge is to render the right half of the rectangle in red, while displaying the full stretched image of the cat on the left half. Here's my current scen ...

What steps are involved in developing a quiz similar to this one?

Check out this interesting quiz: I noticed that in this quiz, when you answer a question, only that section refreshes instead of the entire page. How can I create a quiz like this? ...

Send binary information using Prototype Ajax request

Currently, I am utilizing Prototype to send a POST request, and within the postdata are numerous fields. One of these fields contains binary data from a file, such as an Excel spreadsheet chosen by the user for upload. To retrieve the contents of the file ...

The useEffect function completely overwrites the existing store

My Redux store consists of 3 reducers: let reducers = combineReducers({ config: configReducer, data: dataReducer, currentState: gameStateRecuder}) let store = createStore(reducers, applyMiddleware(thunkMiddleware)); Initially, each reducer in the store i ...

Interact with AngularJS and ASP.NET MVC by invoking controller actions

Previously, I used the following code to retrieve a JSON result from a function before integrating AngularJS: $.ajax({ url: '@Url.Action("getGamedata", "Home")', type: 'GET', dataType: 'json', ...

When the status is set to "Playing," the Discord Audio Player remains silent

So, I'm in the process of updating my Discord audio bot after Discord made changes to their bot API. Despite my best efforts, the bot is not producing any sound. Here's a snippet of the code that is causing trouble: const client = new Discord.Cl ...

Capture various data points in an array with each click

I am currently working on a menu of buttons where users can select multiple options at the same time. My goal is to record all selected buttons in one array instead of individual arrays for each button. The end result I hope to achieve is an array like t ...

What is the method for applying background color to text within a textbox?

I am struggling to phrase this question properly and unable to find the solutions I need on Google. When searching, it only provides information on how to add an entire background color to a textbox, which is not what I am looking for. What I aim to achiev ...

Position items within the dynamically generated div without appending them

Utilizing JavaScript, I dynamically generate a line but struggle to position two balls at both the 1/3 mark from the beginning and end. For reference, please view the image below. I aim to have two balls appear upon pressing enter in the input box. Despite ...

In a React component, clicking on a download anchor tag will open the file in a browser without automatically initiating the

I am currently working on a React component where I have implemented a download function to download a file upon clicking: <a key={file.attachmentId} className="item uploaded" href={Pathes.Attachments.getById(file.attachmentId)} target="_blank" ...

Placing Google Adsense among the content created using a JQuery loop

I have implemented a search function on my website that retrieves results from the database in JSON format. These results are then dynamically displayed by appending a DIV or SPAN element within a loop. $("#btnGetresult" ).click(function(e) { var ...