What is the best way to fill an array with objects that each contain an internal array using data retrieved from a REST API?

I've been searching for a solution online for about an hour now, but I haven't found the right answer yet. So, I decided to share the response I'm getting from the API with you:

[
  {
    "Name": "name1",
    "Title": "Name One",
    "Children": [
      {
        "Name": "Name 1.1",
        "Title": "Name one point one"
      },
     ]

Now, I need this data to fit into a specific format like this:

{
title: 'Name One',
value: 'name1',
key: '1',
children: [
  {
    title: 'Name one point one',
    value: 'Name 1.1',
    key: 'key1',
  },

I have been trying to achieve this using a foreach loop, but it's not working as expected because I need to do all of this within one instance of a loop. Here is what I tried (using vue2):

   created() {
    getData().then(response => {
      const formattedResponse = []
      response.forEach((el, key) => {
        formattedResponse.title = response.Title
        formattedResponse.name = response.Name
        formattedResponse.children = response.Children
      })
    })

Answer №1

Utilize the map method on the main array and employ destructuring assignment to extract properties by key, rename them, and repeat this process with the children array as well. Finally, return the updated array of objects.

const data=[{Name:"name1",Title:"Name One",Children:[{Name:"Name 1.1",Title:"Name one point one"}]},{Name:"name2",Title:"Name Two",Children:[{Name:"Name 1.2",Title:"Name one point two"}]];

const result = data.map((obj, key) => {

  const { Title: title, Name: value } = obj;
  
  const children = obj.Children.map(obj => {
    const { Title: title, Name: value } = obj;
    return { title, value, key: (key + 1).toString() };
  });
  
  return { title, value, children };
   
});

console.log(result);

Answer №2

Your API reply is in JSON format. Simply follow these steps:

var data=JSON.parse(API response);

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

The ng-click event in AngularJS does not function as expected when nested within another ng-repeat loop

I am facing an issue with ng-click in my Angular application (version 1.0.4). The first ng-click works fine, but the second one does not. <div class="menu-group" ng-repeat="module in modules"> <div ng-click="toggle($event, $parent)" ...

Opening a browser tab discreetly and extracting valuable data from it

Greetings to the experts in Chrome Extension development, I am exploring ways to access information from a webpage without actually opening it in a separate tab. Is there a method to achieve this? Here's the scenario: While browsing Site A, I come a ...

develop a Java 2D array

Currently, I have a Java code set up to calculate the average of an array and it's working flawlessly. However, I am looking to make modifications so that it can handle a 2D array (Two-dimensional). import java.util.*; public class Test3{ public st ...

Storing extensive JSON data with AJAX, jQuery, and Java

Currently, I am utilizing jQuery AJAX to call a server-side method and sending a JSON string to the controller. Everything works smoothly when the JSON size is small, but as soon as it exceeds 7kb, the server side rejects the JSON string. I suspect that t ...

Tips for creating a non-blocking sleep function in JavaScript/jQuery

What is the best way to create a non-blocking sleep function in JavaScript or jQuery? ...

Basic event listener function, functional in CodePen but not operating in Chrome web browser

I'm experiencing an issue where event listener functions are not working on my browser (Chrome), but they work fine on CodePen. I've been troubleshooting this for about 2 hours, and I'm seeking some insights. Can anyone help? CodePen Link: ...

Use Google Maps to plan your route and find out the distance in kilometers as well as the

Feeling a bit overwhelmed with the project I'm working on, but hoping for some guidance. We're aiming to create a form where users input a starting point and an ending point, similar to the examples on Google Maps (http://code.google.com/apis/ma ...

Is it feasible to access reference images contained within a zip/tar file using html/javascript with the help of a library?

Although this question may appear similar to others, there is a key distinction that sets it apart. In search of request efficiency rather than space efficiency, lazy loading could be the solution. However, in situations where content needs to be quickly ...

Creating separate Vuex stores for dynamic components

This question really had me stumped for a while. I couldn't find the answer here (asking around didn't help either). However, after conducting some research and seeking advice from various sources, I believe I have finally arrived at a solution t ...

Utilize three.js to set the camera's position and rotation

In my current setup, I have a particular object in view using a PerspectiveCamera. By utilizing OrbitControls, I can navigate around the object, rotate it, pan it, and more. My goal is to reposition the object to a specific location at a specific angle an ...

A guide to using JavaScript to retrieve a CSV file in HTML and store its contents in an array

I am currently working in AngularJs with the objective of uploading a file and saving it as an array using JavaScript. Below is my HTML code: <input type="file" id="uploadFile" name="uploadFile" accept=".csv" required /> <button ng-click="proces ...

Here are some steps for generating a non-integer random number that is not in the format of 1.2321312312

I am looking to create random numbers that are not integers, for example 2.45, 2.69, 4.52, with a maximum of two decimal places. Currently, the generated number includes many decimal places like 2.213123123123 but I would like it to be displayed as 2.21. ...

What is the process for appending a value to an array of JSON objects?

I have a JSON array containing objects which I need to pass the values to the DataTables. [{ _id: '58a2b5941a9dfe3537aad540', Country: 'India', State: 'Andhra Pradesh', District: 'Guntur', Division: ...

Combine various input data and store it in a variable

I am looking for a way to add multiple input text values together and store the sum in a variable. Currently, I can add the values and display it in an id, but I want to assign it to a variable instead. The condition for this variable is described below af ...

Seamless Axios operations even without internet connection in Vue.js

In my Nativescript Vue.js application, there is a functionality where the user clicks on login, Axios makes a call to an endpoint to fetch a token. However, I noticed that when the emulator phone is offline, the Axios call still goes through and the &apos ...

retrieving the result from an asynchronous function in Node.js

Currently, I am using Node.js to query data from Mongodb via Mongoose. Once the data is retrieved, I need to perform some operations on it before sending it back to the client. However, I am facing an issue where I cannot access the return value of the d ...

Creating a scrolling effect similar to the Nest Thermostat

After researching countless references, I am determined to achieve a scrolling effect similar to the Nest Thermostat. I came across this solution on this JSFiddle, but unfortunately, the parent element has a fixed position that cannot be utilized within my ...

Troubleshooting a JQuery accordion malfunction within a table

I am populating the data dynamically. However, the Accordion feature is not functioning correctly. JSFiddle link http://jsfiddle.net/aff4vL5g/360/ Please note: I am unable to modify the HTML structure. Current table Desired output The first accordio ...

Iterating through a JSON object to verify the presence of a specific value

I have a JSON Object and I am looking for a way in Angular 6 to search for the value "Tennis" in the key "name". Can you provide guidance on how to achieve this? { "id":2, "name":"Sports", "url":"/sports" "children":[ { "id":1, ...

Unexpected behavior observed with callback function when inserting a query in Node.js

Having a minor issue with using the POST method and adding an INSERT. The functionality works correctly as shown below, but I am looking to implement a callback after the data has been inserted. Currently, the database is updated successfully, but I am una ...