Reputation: 3578
I've tried googling this with terms such as "fill equivalent for objects" but it insists on only showing me results for Arrays (which makes sense, since this is an array method).
I know if it were an array, I could just do array.fill(0, 0, 28)
;
However, I want to fill an object with a predetermined amount of keys. I could use a loop like;
let dateObj = {};
for(let i; i < 31; i++){
// fill a key in my object with dateObj.i = ''
}
to do this, but wondered if there's an easier way.
My current object looks like this;
04-Apr-19: (40) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
05-Apr-19: [{…}]
Essentially, I want to use it for filling a Graph for the last 30 days. However, as you can see, it only contains data for two days. I therefore need to fill the other 28/29 days.
Any ideas or will I just have to use a loop?
Upvotes: 1
Views: 148
Reputation: 1
Here's a little thing I just whipped up
let obj = {
'04-Apr-2019': [1, 2, 3],
'05-Apr-2019': [4, 5, 6]
};
const fillMonth = (obj) => {
// fix this - it may not be fully cross browser compatible
let d = new Date(Object.keys(obj)[0].replace(/-/g, '/'));
let year = d.getFullYear();
d.setMonth(d.getMonth() + 1);
d.setDate(0);
let last = d.getDate();
let txtMonth = d.toLocaleDateString('en', {month:'short'});
return Array.from({
length: last
}, (_, i) => ({
[`${(i+1).toString().padStart(2, '0')}-${txtMonth}-${year}`]: null
}));
};
let newObj = Object.assign({}, ...fillMonth(obj), obj);
console.log(newObj);
Though, it does rely on having at least ONE key
I'm assuming you want to "fill" a month of keys
most of this code is just to create the "nn-mmm-yyyy" keys for a full month, with null value
then, the trick is, and the core of the answer:
let newObj = Object.assign({}, ...fillMonth(obj), obj);
use Object.assign to do the heavy lifting for you, first, all the keys for every day of the month are added ...fillMonth(obj)
, then the original object is added, overwriting any keys with the values from obj
The rest of the code is really just a quick hack to read the first key, get a date from it, calculate how many days are in that month, and produce an array of objects
Upvotes: 2
Reputation: 4167
There isn't any native function build into the language which does it. However, you can very easily build your own function for it.
Without a loop:
const fillObject = (number, seed = {}, startIndex = 0) => new Array(number).
fill('').
reduce((acc, _, i) => Object.assign(acc, {[i + startIndex]: _}), seed);
console.log(fillObject(28));
console.log(fillObject(26, {'0': '', '1': ''}, 2))
With a loop:
const fillObject = (number, seed = {}, startIndex = 0) => {
const acc = seed;
for (let i = 0; i <= number; i += 1) {
acc[i + startIndex] = '';
}
return acc;
}
console.log(fillObject(28));
console.log(fillObject(26, {'0': '', '1': ''}, 2))
Upvotes: 1