Tips for developing a nested array of objects using a JavaScript loop

Can someone help me with looping an AJAX response to create an array in this format?

"2023-03-30": {"number": '', "url": ""},
"2023-03-30": {"number": '', "url": ""}

The loop I'm using is as follows:

var columns = {};

for (var i=0; i < parsed_data.tasks.length; i++) {
  var mydate = parsed_data.tasks[i].date; 
  columns.push(mydate);
}

console.log(columns);

Unfortunately, this code is not yielding the expected output. Any suggestions on how to make it work?

Answer №1

If you are not receiving the expected response, what outcomes are you currently observing? One potential approach to consider is:

// Initialize an empty object to hold the outcome
var outcome = {};

// Iterate through the AJAX response array
for (i = 0; i < parsed_data.tasks.length; i++) {

  // Extract the date, number, and URL values from each object
  var mydate = parsed_data.tasks[i].date;
  var number = parsed_data.tasks[i].number;
  var url = parsed_data.tasks[i].url;

  // Check if there is a pre-existing object with the same date in the outcome object
  if (!outcome[mydate]) {

    // If one doesn't exist, create a new object with the date as the key and an empty object as its value
    outcome[mydate] = {};

  }

  // Assign the number and URL values to the respective object within the outcome object
  outcome[mydate]["number"] = number;
  outcome[mydate]["url"] = url;
}

// Display the final outcome
console.log(outcome);

Answer №2

If you ever find yourself in need of extracting dates, consider utilizing the Object.keys method as demonstrated below:

const dataList = [
      {"2023-03-30": {"number": '', "url": ""}},
      {"2023-03-30": {"number": '', "url": ""}}
    ];
    const extractedDates = dataList.map(item => Object.keys(item)).flat();
    console.log(extractedDates);

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

Contrasting characteristics of indexing and slicing within numpy structured arrays

Imagine you have a structured array a: import numpy as np a = np.array([1, 2, 3, 4, 5, 6], dtype=[('val', 'i4')]) print(a) [(1,) (2,) (3,) (4,) (5,) (6,)] Now, when it comes to changing one of the entries to a different value, there ...

Learn the ins and outs of utilizing the Ajax jQuery function for passing a string URL and data effectively

Currently, I am working on an ajax jquery function: $.ajax({ url: '/Member/SaveCoordinates/@Model.Id', type: "POST", data: window.image.pinpoints, success: function ...

Rendering issues arise in the app when utilizing browserHistory instead of hashHistory with React Router

I have integrated React Router into my current project in the following way: const store = Redux.createStore(bomlerApp); const App = React.createClass({ render() { return ( React.createElement('div', null, ...

Choosing the right jQuery selector to target a section that contains div elements

Whenever the h2 element within a section is clicked, I want all the fields in that section to be displayed. For example, if the user clicks on 'Contact Information', the three form inputs (fields) below the Contact Information heading should appe ...

Trigger a jQuery event when a particular element has finished loading

Is there a way to globally detect when any element (such as textarea) is displayed on the page in order to perform a specific action? The element could also be added dynamically through an AJAX request. // This code snippet is just an illustration of the ...

Border color options for select boxes

Currently, I am working on my first Django-bootstrap project and dealing with a select box. I am trying to customize it so that when clicked, the border of the select box and its options turns yellow, which is working well. However, there is an additional ...

Combining a random selection with a timer in JavaScript for a dynamic user experience

Currently, I am developing a Twitter bot using JavaScript, Node.js, and the Twit package. The goal is for the bot to tweet every 60 seconds with a randomly selected sentence from an array. When testing the timer and random selection function individually, ...

What is the syntax for implementing an if-else statement?

Just starting with algolia and looking for a hit template. Please take a look at the script below for the text/html template needed: <script type="text/html" id="hit-template"> <div class="hit"> <div class="hit-image"> <i ...

Highlight the active page or section dynamically using HTML and jQuery - How can it be achieved?

What am I trying to achieve? I am attempting to use jQuery to dynamically highlight the current page from the navigation bar. Am I new to jQuery/HTML? Yes, please excuse my lack of experience in this area. Have I exhausted all resources looking for a sol ...

Updating WordPress div content based on selected post type using dropdown menu

I am in the process of developing a WordPress plugin that will generate a custom post type and widget for users to add to their websites. The goal is to have the widget display a dropdown select box with titles of each post, and when a title is selected, t ...

Issue with Bootstrap Navbar dropdown functionality not functioning correctly in browsers, but working fine on Codepen

I'm encountering an issue with a dropdown menu in the navbar of my document. The dropdown menu works fine in my codepen but not in my text editor (Sublime). I've tried various solutions and couldn't find a fix, so I'm reaching out here ...

Instructions on invoking a function from one controller within another controller

Is it possible to invoke a function from one controller in another controller? I attempted the following but encountered failure: <div ng-app="MyApp"> <div ng-controller="Ctrl1"> <button ng-click="func1()">func1</button> ...

IntelliJ is not able to detect certain JS libraries

Currently, I am working on an NDV3 AngularJS graph demo using IntelliJ. To start off, I have created a standard HTML file named index.html and included all the necessary AngularJS and NDV3 libraries in a folder called bower_components located within the r ...

Unable to execute a JavaScript function when triggered from an HTML form

This is the code for a text conversion tool in HTML: <html> <head> <title> Text Conversion Tool </title> <script type="text/javascript"> function testResults(form) { var str = form.stringn.value; var strArray = str.split(" ...

Using SimplyJS and XML: extracting the value of a specific key

Hey there, I wanted to update you on my progress with the Pebble Watch project. I've switched over to using an official external API to make HTTP requests for values, and now I'm receiving results in XML format instead of JSON. Here's a ...

Tips for resolving the error message "Uncaught TypeError: Cannot read property '0' of undefined" in React rendering

When I try to map through my list in the render function, it doesn't work, even though it works fine within my component class DesktopList extends Component { constructor(props) { super(props); this.state = { i ...

Using ui-grid to show cells as drop-down menus

I have a ui-grid example where one of the columns represents gender ('Gender': male, female...). The json data binding to the grid only contains code types like (1, 2, 3...). However, I want to display the gender name such as 'male' if ...

Problem with JSON parsing in jQuery on Internet Explorer 8

I am struggling to pinpoint where my mistake is in this code snippet: Javascript: $(document).ready(function(){ $.getJSON('ajax/data.json', function(data) { $.each(data.results, function(i,item){ alert ...

the function does not output any value

I am currently facing an issue with my function called IsValidUrl(). This function is supposed to return values based on a certain condition (either false or true). However, there seems to be another function within it that is preventing the values from be ...

Summoning within a rigorous mode

I am facing an issue with my configuration object: jwtOptionsProvider.config({ tokenGetter: (store) => { return store.get('token'); }, whiteListedDomains: ['localhost'] }); In strict mode, I ...