A
A
Aleksandr2018-04-28 14:54:10
JavaScript
Aleksandr, 2018-04-28 14:54:10

How to rename properties in an object?

There is an object:

{
    "id": '',
    "name": ''
}

Need to do:
{
    "value": '',
    "label": ''
}


I wrote like this:
computed: {
...mapState({
      categories: state => state.main_page.NEWS
}),
getCategories() {
      let arr = [];
      let categories = this.categories;
      categories.forEach(function(obj) {
        obj['value'] = obj['id'];
        obj['label'] = obj['name'];
        delete obj['id'];
        delete obj['name'];
        arr.push(obj)
      })
      
      return arr
    }
}


Everything works, but at the same time this.categories itself has changed.
How to make sure that old keys remain in the source and objects are created with new ones?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-04-28
@Sashjkeee

It is not necessary to give computed properties names that start with "get" - after all, they are properties, not methods.
There is no need for an additional calculated property, which you just have a reference to an array in storage - immediately create a new array, the properties of the elements of which will be renamed as you see fit:

computed: {
  categories() {
    return this.$store.state.main_page.NEWS.map(n => ({
      value: n.id,
      label: n.name
    }));
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question