0

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!

1
  • 1
    arr.forEach(e => h.data[e] = 0 ) Commented Jun 13, 2018 at 6:23

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for explaining step by step! In case you know, what would be more computationally efficient: my naive approach or your advanced one (assuming a size-able default array to set)? Or they are almost equal? I will wait for a few more hours to see who comments with more suggestion and then accept one of the answers. Hope you understand. :)
what would be more computationally efficient , the one you're using should be more efficient. I just added another way to do it. :)
Thank you for the follow-up response. :) I'm glad that I learned a more advanced way to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.