[Vuejs]-How to set value as an Object in JS ES6 new Map (key, value) pair

3๐Ÿ‘

โœ…

Iโ€™ll ignore the syntax errors (missing brackets and unquoted id values) assuming this is not copied from your actual code.

You can use the Map() constructor with an iterable like an array to set multiple elements during initialization like

let map = new Map([
  ['2018',  { foo: 'bar }],
  ['2019',  someVariable]
]);

You cannot do the same with Map.prototype.set().

So while you could do it like this

let books = new Map([[
  '2018', {'a' : {id: 'userid', name: 'a'}}
], 
[
  '2019', {'a': {id: 'userid', name: 'a'}}
]])

your senior (and soon you) is probably gonna be very happy if you start breaking things down into very explicit, small and manageable steps instead of throwing it all into one long line.

Give an approach like this a try and see how you like it

let books = new Map()
books.set('2018', {'a' : {id: 'userid', name: 'a'}})
books.set('2019', {'a' : {id: 'userid', name: 'a'}})
๐Ÿ‘คTommyF

0๐Ÿ‘

Example using Map() in VueJS.

export default {
  ...
  data: function() {
    return {
      books: new Map([
        ["2018", { a: { id: "userid", name: "a" } }],
        ["2019", { b: { id: "userid", name: "b" } }]
      ])
    };
  },
  mounted() {
    this.books.forEach((dict, year) => {
      for (const key in dict) {
        const obj = dict[key];
        console.log(`O:--Get Book Info--:year/${year}:id/${obj.id}:name/${obj.name}`);
      }
    });
  }
};
๐Ÿ‘คNeda Peyrone

Leave a comment