Troubles with indexing a JavaScript array

My dilemma lies in extracting and storing specific data from a JSON object into an array. I am struggling to organize the information as desired within the array structure outlined below:

Array = [0]['start'] = 'Date1', [0]['end'] = 'Date2', [0]['name'] = 'NameN'

With the index of the array being represented by n

As you can envision, there will be multiple entries in this array that can be accessed based on their respective indexes.

var array = new Array();
var label;

data = JSON.parse(data);
$.each(data.rows, function(i, row) {  
    $.each(row.c, function(j, item) {
        if(j == 0){
           label = 'start';
        }
        if(j == 1){
           label = 'end';
        }
        if(j == 2){
           label = 'name';
        }

        if(j == 0 || j == 1 || j == 2){
            array[i]["test"] = item.v;
            //console.log('array['+i+']['+label+'] = '+ item.v);
        }
        //console.log(item.v);
    });
});

I'm seeking guidance on achieving this functionality in JavaScript. Thank you!

Edit: Initially, my JSON looked like this

{"cols":[{"id":"","label":"start","pattern":"","type":"datetime"},{"id":"","label":"end","pattern":"","type":"datetime"},{"id":"","label":"content","pattern":"","type":"string"}],"rows":[{"c":[{"v":"Date(2014, 3, 25)","f":null},{"v":"Date(2014, 4, 2)","f":null},{"v":"Subgoal A","f":null}]},{"c":[{"v":"Date(2014, 4, 2)","f":null},{"v":"Date(2014, 4, 9)","f":null},{"v":"Subgoal B","f":null}]}],"p":null}

Answer №1

JavaScript does not support multi-dimensional arrays, but you can achieve similar functionality by using an array of objects. Simply create an output array, iterate over the JSON data, and add a new object to the array for each iteration.

var output = [];
for (var index = 0, length = jsonData.items.length; index < length; index++) {
  var item = jsonData.items[index];
  output.push({
    name: item.name,
    value: item.value
  });
}

for (var j = 0, k = output.length; j < k; j++) {
  console.log(output[j].name);
}

OUTPUT

Name: John, Value: 25
Name: Jane, Value: 30

DEMO

You can access individual objects in the array by their index, like so:

output[1] // { name: "Jane", value: 30 }

To retrieve objects based on a specific key-value pair, you can set up a function like this:

function findObject(key, value) {
  return output.filter(function (element) {
    return element[key] === value;
  });
}

DEMO

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

Is it possible to utilize AJAXToolKit and Jquery on a single webpage?

Is it possible to utilize both AJAXToolKit and jQuery on a single page? For example, let's say we have ScriptManager in the same page along with including ...

How can Angular 7 be used to accept a ZIP response from an API?

My attempt to download a zip file to my local system using Angular's API response with the desired type as zip has been unsuccessful. Despite specifying the correct content-type and Accept headers, I keep encountering errors. a.service.ts download( ...

Exporting the Matter.js engine world data to JSON format

Is there a way to save my engine.world Object in an exportable format? I attempted converting it to a JSON string using JSON.stringify(engine.world) but encountered issues with the circular structure. Are there any solutions for this problem, or alternativ ...

Requesting data from a JSON array of objects leads to an undefined result

<!DOCTYPE html> <html> <head> <title>Practice</title> </head> <body> <script> const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd7 ...

Using Ajax calls in NodeJs to access the database

I have been working on a project involving a MongoDB database that contains information about different countries. I have implemented various pie charts to display this data, but now I want to give users the option to choose which specific year they would ...

assert.deepPartiallyEqual method designed for comparing two objects in an asymmetric manner

I've been struggling to come up with suitable names for this function, but let me explain what I'm looking for: I need an assertion function similar to assert.deepEqual(obj1, obj2), but instead of recursively comparing obj1 with obj2, it should ...

There seems to be an overload of commas showing up in my array

I recently developed a program that captures user inputs to create an array and then reverses the array. However, I encountered an issue with the printing of values separated by commas as it is adding one extra comma. Below is the snippet of my code: #inc ...

How to utilize JavaScript to convert a string into a function name

In this specific scenario, I am required to trigger a function based on the data attributes associated with an HTML element. function func1(arg1){ alert("func1"); } function func2(arg2){ alert("func2"); } jQuery(document).on('click', & ...

Searching for a specific element in jQuery by querying a string

I have a situation where an ajax request is made to send text using the POST method to another PHP page. This PHP page then converts the text into markdown format and sends it back. Here's an example of what it looks like: "<p>Meep, meep, <e ...

What is the best way to duplicate and delete the final child element using jQuery?

Can someone help me troubleshoot this code that is supposed to clone and remove the last child of a ul element? It doesn't seem to be working as expected. $(document).ready(function () { var tmp1 = ''; var tmp = '<ul>< ...

What is causing the repetition of values in the output from my .ajax() request?

I'm feeling lost with my code snippet. I am attempting to display values from a json request using .ajax(). Here is the code causing trouble: $.each(posts, function(k, v){ $("section ul").append("<li><p>" + v.webTitle + "</p>&l ...

As soon as I inserted the image, the text vanished into thin air

The phrase "welcome" is not displaying after I included the av tag <!DOCTYPE html> <html> <style> @font-face { font-family: OpenSans; src: url(OpenSans-Bold.ttf); } * { ...

Unable to update React state on a component that is unmounted while utilizing Redux

Utilizing Redux for managing a global Dialog component, I am passing the child components to the Dialog component through Redux actions. You can find a functional example in this codesandbox: https://codesandbox.io/s/suspicious-keldysh-uuolb?file=/src/App ...

Navigating the world of vue-toastification is as easy as pie

I recently made the transition from using vue 3 to nuxt 3 for my project. In vue, I was utilizing the vue-toastification module but after migrating to nuxt, I'm facing difficulties importing it correctly into my code. Here's a snippet of how I wa ...

Animate a list to expand and collapse the menu options

Here's the concept I'm aiming to achieve: When "PORTFOLIO" is clicked, smoothly push down everything on the page; New links should fade in smoothly; If "PORTFOLIO" is clicked again, reverse all animations. This is my current code snippet: $( ...

Leveraging AngularJS $promise in conjunction with NgResource

As I delve into the world of AngularJS, I have encountered promises which have proven to be quite beneficial in my learning journey so far. Now, I am eager to explore the optional library resource.js in AngularJS. However, I stumbled upon examples that lef ...

Want to learn about Google Apps Script Web App? Join us to dive into AJAX, leverage

I'm attempting to follow the steps outlined in "Example 3: Web Response" on "this SparkFun tutorial" After implementing the code on script.google.com, I encountered an issue where I couldn't see the pin readings. Can someone provide assistance w ...

Switched from btao to Buffer, however encountering a TypeError while trying to push to Vercel

I am currently working on an application in Next.js where I need to encode my image to base64. Initially, I used btao and it worked well until I tried deploying to Vercel, which resulted in an error stating that btao was undefined. After researching a solu ...

What is the method for retrieving the input value once it has been obscured with asterisks (*)?

Currently, I am in the process of developing a Vue application that will display * characters instead of revealing the actual input entered by the user (similar to a password field). While I have successfully implemented this functionality, I am encounteri ...

dynamically import a variety of components in vue.js and nuxt depending on certain conditions

Is there a way to implement dynamic imports for all 3 components in this scenario? Each component has different props, so using the switch option in the computed method is not feasible. I have come across solutions for using a single component dynamically ...