Home > Enterprise >  Loop through an array and push it into array of object javascript
Loop through an array and push it into array of object javascript

Time:11-15

So i try to loop an Array and push it into object within this code:

   const past7Days = [...Array(7).keys()].map(index => {
var date = new Date();

  const local = new Date();
  local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
  local.setDate(date.getDate() - index);

  return local.toJSON().slice(0, 10);
});
let data={};
let arr=[]
for (var i = 0; i < past7Days.length; i  ) {
    console.log(past7Days[i]);
  return arr.push(data["key"] = past7Days[i]) 
}

what i expected is :

[{key:"date"},{key:"date2"}]

can somebody tellme where did i do wrong here

CodePudding user response:

Assuming you want exactly one array where the elements are like {"key": <string representation of a date> }, you can try this:

const past7Days = [...Array(7).keys()].map(index => {
var date = new Date();

  const local = new Date();
  local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
  local.setDate(date.getDate() - index);

  return local.toJSON().slice(0, 10);
}); 
let arr=[]
for (var i = 0; i < past7Days.length; i  ) {
    // console.log(past7Days[i]);
    arr.push( {key: past7Days[i] } ) 
}
console.log(arr);

CodePudding user response:

In your attempt there is only one such object created (data) and the assignments to data[key] just keep overwriting the same object's property. Moreover, that push will not push an object, but the string that is assigned.

You can create each object immediately in your first iteration, with a { key: string-value } object literal and returning that.

Unrelated, but you should not use getTimezoneOffset like that. In boundary cases (like when daylight saving switches on the same day) it can have undesired results. Instead consider that you can convert a date to a string with respect of the current locale's timezone. For instance, the Swedisch locale also uses "YYYY-MM-DD" format (like toJSON), and when used with toLocaleDateString it will use the locale's date:

const past7Days = Array.from({length: 7}, (_, index) => {
    const local = new Date();
    local.setDate(local.getDate() - index);
    return { key: local.toLocaleDateString('en-SE') };
});
console.log(past7Days);

  • Related