david
david

Reputation: 6785

How to create a dictionary using a for loop in javascript?

I have the following:

  children: [
    {
      name: 'test',
      path: 'test',
      meta: {
        label: 'test',
        link: 'test'
      },
      component: lazyLoading('test/basic')
    },

    {
      name: 'test',
      path: 'test',
      meta: {
        label: 'test',
        link: 'test'
      },
      component: lazyLoading('test/Basic')
    },

    {
      name: 'test',
      path: 'test',
      meta: {
        label: 'test',
        link: 'test'
      },
      component: lazyLoading('test/Basic')
    }
  ]

I want to follow this structure, but programmatically create each dictionary using each record returned from an API call.

example api call

function getData() {
    axios.get(Url + input.value)
    .then(function (response) {
        json_data = response.data;
    });
}

so in python this would probably look something like:

test_list=[]

for item in json_data:
    dict = {
           name: item.name
           path: item.path
           meta:  {
             label: item.label,
             link: item.link,
                  },
           component: lazyLoading('testitem/basic')
           },
     test_list.append(dict)
children: test_list

How can I accomplish this in javascript? I'm having a real hard time learning javascript after doing python.

UPDATE:

This is the full code block that I am working with.

export default {
  name: 'test',
  meta: {
    icon: 'fa-android',
    expanded: false
  },

  children: [
    {
      name: 'test',
      path: 'test',
      meta: {
        label: 'test',
        link: 'test'
      },
      component: lazyLoading('test/Basic')
    }
  ]
}

Upvotes: 0

Views: 4151

Answers (1)

Boris Lobanov
Boris Lobanov

Reputation: 2454

You were very close:

const children = [];
json_data.forEach(item => {
    const dict = {
       name: item.name,
       path: item.path,
       meta:  {
           label: item.label,
           link: item.link,
       },
       component: lazyLoading('testitem/basic'),
    }
    children.push(dict);
});

Upvotes: 1

Related Questions