Creating an array within a for loop in JavaScript: A step-by-step guide

Coming from a Python background, I am embarking on the journey to learn basic concepts in JavaScript.

Currently, I have the following code snippet:

{
  name: 'Jobs ',
  path: '/plat/jobs',
  meta: {
    label: 'jobs',
    link: 'jobs/Basic.vue'
  },

My goal is to create this block for each element in a list using a for loop (including the curly brackets).

In Python, achieving this would look something like:

for i in items:
    {
      name: i.name,
      path: i.path,
      meta: {
        label: i.label,
        link: i.link
     }

How can I accomplish this in JavaScript? What exactly is the data type of this object? Is it simply a JavaScript dictionary?

  children: [
    let new_items = items.map(i => ({
      name: i.name,
      path: i.path,
      meta: {
        label: i.label,
        link: i.link
      }
    }));

    console.log(new_items);
      component: lazyLoading('android/Basic')
    }
  ]
}

I suspect that this approach won't work as I need each object listed under children individually.

Answer №1

Here is a demonstration of working with an array of objects to create a new array of objects. In JavaScript, an object can be compared to a hash, dictionary, or object in other programming languages.

let items = [{
  name: 'foo',
  path: 'foopath',
  label: 'foolabel',
  link: 'foolink'
}, {
  name: 'bar',
  path: 'barpath',
  label: 'barlabel',
  link: 'barlink'
}];

let new_items = items.map(i => ({
  name: i.name,
  path: i.path,
  meta: {
    label: i.label,
    link: i.link
  }
}));

console.log(new_items);

It's worth noting that there is no need for a new array as you can directly modify the existing object:

let items = [{
  name: 'foo',
  path: 'foopath',
  label: 'foolabel',
  link: 'foolink'
}, {
  name: 'bar',
  path: 'barpath',
  label: 'barlabel',
  link: 'barlink'
}];

items.forEach(i => {
  i.meta = {label:i.label, link:i.link};
  delete i.label;
  delete i.link;
});

console.log(items);

Answer №2

If I were to transform a list of items, my go-to method would be using the list.map function.

items.map(item => {
    return {
        title: item.title,
        url: item.url,
        details: {
            description: item.description,
            link: item.link
        }
     }))

By utilizing this approach, a new list with the specified structure will be returned.

It's worth noting that further simplification can be achieved by using an implicit return:

items.map(item => ({
    title: item.title,
    url: item.url,
    details: {
        description: item.description,
        link: item.link
    }
}))

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

Challenges with Asset Management in Vite Compilation Result

I'm encountering a problem with structuring assets in the output directory while utilizing Vite for my project. I have set up the output.assetFileNames option to categorize assets into subfolders based on their types (css, fonts, img, js), but it&apos ...

Error: Unable to access undefined properties while trying to read 'add' value. Issue identified in the code related to "classlist.add" function

I am currently facing an issue where I receive the error message: Uncaught TypeError: Cannot read properties of undefined (reading 'add') when trying to add a class to a div using a button. After researching on Stack Overflow, I stumbled upon a ...

Ensure that the content remains at the center of the screen, but is dynamic and changes

I have a unique concept I want to experiment with, but I'm unsure of the best approach to take. My idea involves centering content on the screen and instead of having it scroll off and new content scroll in, I would like it to stay centered and smoot ...

Create a helper function within a React application that integrates with Redux to enhance

I am new to working with React and Redux. In my previous projects using jQuery, I would create functions like the ones below: errorHandle (code) { if(code = 1){ $('.popUpA').show() } ... } callAPI (){ //Do AJAX call //If Error , ...

JSON.Parse function does not return a valid value

I'm currently developing a polling system. Once a user submits their answer choice, I expect to receive JSON data containing all the answers for display purposes. Upon submitting the AJAX form, the JSON response is as follows: [{"answer_1":0,"answer ...

What is the process for setting up FastAPI to handle server-side rendering for Vue 3?

Is it possible to achieve server-side rendering with FastAPI similar to how it's done with node.js and Vue SSR? Are Jinja2 templates or SPA the only options for rendering dynamic pages? Challenges: Avoiding SPA for better SEO Issues with excessive p ...

Incorporating Vue3 Components within Laravel Blade Using Vite

After transitioning to Vite for my Laravel 9 project, I encountered an issue with loading Vue2 components directly into blade files within HTML code. With Vite's different loader behavior, it now requires loading the entire app into the #app element i ...

Is it possible to develop a higher order component or compose a function that takes in a component and seamlessly incorporates and utilizes extra properties within it?

We've developed a unique component that generates a customized textfield (with our own custom CSS and props) in the following manner: const customTextFieldAvailable = (props) => { const { handleOnchange, onBlur, ...other } = props; return ( ...

Storing user input with AngularJS

I have a form below that I am trying to save. Please review my HTML code for the form. HTML <form ng-submit="save()"> <input type="text" ng-model="user.name"/> <input type="text" ng-model="user.age"/> <input type="text" n ...

How can I show the MySQL "result" object to the user using express-handlebars?

In my Node.js code, I currently have a query that looks like this: app.get('/fav/books', function(req, res){ var sql = ("SELECT title, pictureUrl, author, description, genre FROM books") connection.query(sql, function(err, result){ if(err) ...

An error has occurred in the Nuxt request. The value used as a weak map key

When attempting to run the command npm run dev, I encountered an error. Despite this issue, the app runs smoothly locally. However, during production, the following error occurs. Any assistance would be greatly appreciated! :) ...

Converting a MySQL date field into a specific format using PHP

Similar Question: PHP convert one date into another date format I am looking to convert the date 2011-09-06 to a format like 2011-09-06T00:00:00.0000000 I searched online but couldn't find a clear solution. Your help is greatly appreciated. ...

Tips for updating the input name in Vue.js

I need assistance with implementing a dynamic form where input names must be in array format and the array number should increase automatically for posting purposes. Here is my code snippet: <!doctype html> <html lang="{{ str_replace('_&apo ...

I'm currently navigating through various sections of HTML, making sure to keep track of which

I am faced with a situation where I have 2 HTML sections that both share the same ID. Unfortunately, this is out of my control as it is being generated by a third-party CMS. Currently, I have a simple code running to determine how many html sections there ...

Modify the hue of the div as soon as a button on a separate webpage is

Looking for assistance with a page called "diagnosticoST" that contains four buttons (btn-institucional, btn-economico, btn-social, btn-natural). These buttons have different background colors until the survey inside them is completed. Once the user comple ...

Vue JS encounters difficulties when attempting to lazy load various images from a randomized image URL

I've implemented a code snippet for lazy loading images with different URLs: <img src="https://source.unsplash.com/1600x900/?hotel,booking.com?v=1" loading="lazy" /> <img src="https://source.unsplash.com/1600x900/?hot ...

Generate and store text inputted from contenteditable

As I embark on creating my own custom rich text editor, I have a couple of questions regarding its functionality. First and foremost, is it possible to prepopulate the text area with content? Additionally, I'm seeking guidance on how to save and utili ...

converting HTML values to TypeScript

I'm a beginner with Angular and could use some assistance. Currently, I have two components - one for the index and another for navigation. Within the index component, there are subcomponents that change based on the value of a variable called produ ...

The server failed to trigger the SignalR method

There are two methods on the server that can be invoked, both are very similar. However, only one of them (SubscribeToWatchlist) is being executed on the server side when called. The UnsubscribeFromWatchlist method is not working as expected. ASP.NET Cor ...

Javascript - EventListener triggers responses to clicks on the entire span on both its left and right sides

I recently delved into the world of JavaScript and decided to challenge myself by creating a TicTacToe game for educational purposes. If you're curious about what my simple game looks like so far, here's a link to it: In the game, I prompt the ...