What is the best method for initializing a JavaScript array in my specific scenario?

I had the idea to structure an object similar to this:

var collection = [{
    'title': 'title1',
    'content': {
        'subtitle': 'sub1',
        'contents': 'sub content 1'
    }
}, {
    'title': 'title2',
    'content': {
        'subtitle': 'sub2',
        'contents': 'sub content 2'
    }
}, {
    'title': 'title3',
    'content': {
        'subtitle': 'sub1',
        'contents': 'sub content 1'
    }
}];

The array I am working with looks like this

var section = [];
for (var i = 0; i < data.length; ++i) {
    section['title'] = data.title;  //data.title represents title1 to title 3
    for (var j = 0; j < data.sections.length; ++j) {
        //data.sections[j].content represents {'subtitle':'sub1', 'contents':'sub content 1'}
    }
}

I'm struggling to adjust my code to match the desired object structure. Can someone lend a hand? Much appreciated!

Answer №1

Is it possible that the following approach will be effective? Since I don't have access to the data array, I've had to make some educated guesses.

var section = [],
        obj,
        d,
        s;
      for (var i = 0; i < data.length; ++i) {
          d = data[i];
          obj = {};
          obj.content = {};
          obj.title = d.title;
              for (var j = 0; j < d.sections.length; ++j) {
                  s = d.sections[j];
                  obj[s.subtitle] = s.content;
              }

        section.push(obj);
      }

Answer №2

One way to achieve the desired result is by utilizing the reduce function, with a slight modification:

const newObj = array.reduce((accumulator, value, index) => {
   accumulator[index] = value;
   return accumulator;
}, {});

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 context provider in Next.js wraps the App component with a layout component specific to each page, resulting in data

Within my project, I have an authentication context component wrapping the main app component. Simultaneously, I am also attempting to implement a page-specific layout component based on the Next.js documentation found here. I'm unsure if my approach ...

Dynamically getting HTML and appending it to the body in AngularJS with MVC, allows for seamless binding to a

As someone transitioning from a jQuery background to learning AngularJS, I am facing challenges with what should be simple tasks. The particular issue I am struggling with involves dynamically adding HTML and binding it to a controller in a way that suits ...

Error message saying 'Callback has already been invoked' returned by an async waterfall function

I'm facing an error that I understand the reason for, but I'm unsure how to resolve it. Here's a breakdown of my initial function: Essentially, I am making a get request for all URLs stored in the database and then, for each URL response, I ...

PHP array manipulation to filter specific elements

In my code, I am using a foreach loop to reorganize data based on location and appointment dates/times: $temp = []; $remappedData=[]; $intCurrentIndex = -1; foreach ($result as $value) { if(isset($temp[$value['Location']] ...

Utilizing AngularJS to dynamically insert HTML content with directives and data-binding

I have a specific scenario where I am dealing with a list populated using ng-repeat. In this setup, I also have a directive that handles formatting based on the content type field. My objective is to implement directives on the injected HTML. Is there a ...

Organizing and recycling React styled-components and native elements

As a backend engineer transitioning to frontend development, I am currently learning React and exploring styled-components for styling components. However, I am facing challenges in using styled-components with native React components and updating them in ...

Struggling with getting my Vue-CLI app deployed on Heroku

After diligently following all the steps outlined in this tutorial: https://codeburst.io/quick-n-clean-way-to-deploy-vue-webpack-apps-on-heroku-b522d3904bc8 I encountered an error message when checking my app at: The error indicated: Method Not Allowed ...

Commit to persevering until you achieve success

I'm currently working with native node.js Promises and did not find any useful information in this thread. Essentially, I am dealing with a function that looks like this: var foo = foo (resolve, reject) { return obj .doA() .doB() ...

Exploring the method to retrieve data on the server side through Express when it is shared by the client within a put request

Here is the angular http put request I am working with: sendPutRequest(data) : Observable<any>{ return this.http.put("http://localhost:5050", data).pipe(map(this.handleData)); } After making this call, the server side method being invoked is ...

Overlay a translucent image on top of another using JavaScript

Is it feasible to overlay a transparent-background image onto another image using JavaScript? For example, if you have a website featuring various product pictures and some of these products are recalled, can you superimpose the Do-Not-Enter sign (circle-w ...

Ways to disperse items within another item

I have an inner object nested inside another object, and I am looking to extract the values from the inner object for easier access using its id. My Object Resolver [ { _id: { _id: '123456789', totaloutcome: 'DONE' }, count: 4 }, { ...

Obtain the data from the array and incorporate it into the fresh PHP code

Having a major issue as I am unsure of how to extract values from an array where the value is transformed into the key in a new array. The original array is presented below: Array ( [0] => Array ( [ID] => 250602 ...

Changing a string-stored array into a List object in JavaString

Here is a messy nested list that I need to convert into a list of numbers: nested_list = [ ["[63]"], ["[61]"], ["[7]"], ["[63]"], ["[80, 18]"], ["[80, 43, 18, 20]"] ] I know it's ...

Having trouble with my Slack Bot development due to an unexpected error

While attempting to create a Slack Bot in Node, I consistently encounter an error when running npm start in my terminal: The error seems to be located in the Vow.js file. Despite double-checking everything, I can't seem to pinpoint the issue. For gui ...

Emphasizing the text while making edits to an item within the dhtmlx tree

Whenever I need the user to rename an item on the tree, I trigger the editor for them: tree.editItem(tree.getSelectedItemId()); However, I want the text in the editor to be automatically selected (highlighted). Currently, the cursor is placed at the end ...

php generate an array with a variable number of elements

How can I create an array with a random number of values between 2 and 5, where each value is 50? Is there a simple way to achieve this? For example: $array = array(50, 50, 50) $array = array(50, 50, 50, 50) ...

Guide to showing just the initial and final elements of an array employing a foreach loop in PHP

Looking for a way to display only the first and last exam score from an array of student exam scores when a student makes a selection. Is there a more efficient method to achieve this using a foreach loop in PHP? Here's what I have so far, but I fee ...

I am looking to retrieve data from the Graph API JSON and gradually refine my search to achieve successful

I am looking to retrieve data from the "fb_page_categories" endpoint, which provides an array of categories a page can be categorized under. The format for this request is as follows: GET graph.facebook.com /fb_page_categories? Once this request is mad ...

How to pass an item as a parameter to a computed property in Vue.js, and have it return a sorted child array within a

After spending some time searching on Google, I am still struggling to find a solution for this issue. I have a list of "Intents" that contain nested lists of "Entities" created using v-for loops. The Intents are already computed, but now I need to dynam ...

What is the best way to determine the value of a variable specific to my scenario?

Using the Angular framework, I am trying to determine if the data variable updates when a button is clicked. Here is an example: <button ng-click='change()'>{{data}}</button> I want to verify if the data changes or log the data var ...