[Vuejs]-How to create an array in for loop in javascript?

3👍

Included is an example that operates on an array of objects, returning a new array of objects. An object is overloaded in JavaScript, but in this case it is synonymous in other languages to a hash, object, or dictionary (depending on application).

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);

That said, a new array is not necessary since it’s possible to edit the object directly:

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);

1👍

I would use the list.map function

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

This will return a new list of items as specified

NOTE: this can be simplified further with an implicit return

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

Leave a comment