Chawchawchaw
Chawchawchaw

Reputation: 233

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

I've finished my first small Vue project and my senior told me to re-write it with the new hardcoded data structure using new Map(key-value pair); and value as objects.

JS and Vue are new things for me so I've looked it up a lot and saw some comments that the structure I need to do is impossible. However our company uses data structure like that and I need to it...

what I'm trying to do is a simple book list app. 5 people can add book(s) per year and it has to be sorted by the year. The scope of sorting is getting corresponding data when any year in calendar is clicked.

I used filter() but he said adding same data(year) into an Object in Array is a bad idea because it will make slow the process. We deals with Big and Real time data. update cycle is 1 sec, 24/7/365.

If it's impossible then could you please let me know any hints to do it right??

var books = new Map();
books.set(['2018', {'a' : {id: 'userid', name: 'a'}, 'b': {id: userid, name: 'b'}}], ['2019', {'a': {{id: 'userid', name: 'a'}, 'b': {id: userid, name: 'b'])

Upvotes: 0

Views: 1117

Answers (2)

Neda Peyrone
Neda Peyrone

Reputation: 350

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

Upvotes: 0

TommyF
TommyF

Reputation: 7160

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'}})

Upvotes: 3

Related Questions