简体   繁体   中英

Set default values in a JavaScript hash using values from an Array as keys

Suppose I have a hash h and an array a like this:

h = {'data': {}};
arr = ['2017-01-01', '2017-02-01','2017-03-01', '2017-04-01', ....];

What is the most concise and efficient way to construct a default hash table as below in JavaScript:

// desired outcome for 'h'
h = {
 'data': {
    '2017-01-01': 0,
    '2017-02-01': 0,
    '2017-03-01': 0,
    '2017-04-01': 0,
    //...there can be more date values here
  }
}

I have implemented the solution below, but would like to know if there is more JavaScript-y (and hopefully more efficient) way to accomplish below:

arr.forEach(function(a) {
  h['data'][a] = 0;
});

Thanks in advance for your suggestion/answers!

You can first convert your array into object with .reduce like

arr.reduce((o, key) => ({ ...o, [key]: 0}), {})

this will return you an object of form

 {
    '2017-01-01': 0,
    '2017-02-01': 0,
    '2017-03-01': 0,
    '2017-04-01': 0,
    //...there can be more date values here
  }

Now, you can simply assign this object to your h.data with Object.assign like

 var h = {'data': {}}; var arr = ['2017-01-01', '2017-02-01','2017-03-01', '2017-04-01']; h.data = Object.assign(arr.reduce((o, key) => ({ ...o, [key]: 0}), {})); console.log(h) 

ps: in case you don't know ... is called spread operator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM