对象的.fill()等效项

时间:2019-04-08 12:19:29

标签: javascript arrays object

我尝试用诸如“对象的等效填充”之类的术语进行搜索,但是它坚持只向我显示数组的结果(这是有道理的,因为这是array method)。

我知道它是否是一个数组,我可以做array.fill(0, 0, 28);

但是,我想用预定数量的键填充对象。我可以使用类似的循环;

let dateObj = {};
for(let i; i < 31; i++){
  // fill a key in my object with dateObj.i = ''
} 

要这样做,但想知道是否有更简单的方法。

我当前的对象看起来像这样;

04-Apr-19: (40) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
05-Apr-19: [{…}]

基本上,我想用它来填充最近30天的图表。但是,如您所见,它仅包含两天的数据。因此,我需要填补其他28/29天。

任何想法还是我只需要使用循环?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

执行该操作的语言中没有内置任何本机函数。但是,您可以轻松地为其构建自己的功能。

没有循环:

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

带有循环:

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