Home > Blockchain >  Store object data into array in JavaScript
Store object data into array in JavaScript

Time:03-12

I'm making an app like Carendly.

I have this kind of object data which shows availability.

{
friday: {},
monday: {1: '09:00-12:00', 2: '13:00-15:00'},
saturday: {1: '08:00-15:00'},
sunday: {},
thursday: {},
tueday: {},
wednesday: {1: '09:00-12:00', 2: '13:00-15:00'}
}

and this should store in arrays like below. How can I make it happen?

Arrays
[],// Sunday 
['09:00-12:00', '13:00-15:00'],// Monday
[], // Tuesday
and so on

Thank you for your help!

CodePudding user response:

try this

var result = {
  friday: {},
  ...
  wednesday: { 1: "09:00-12:00", 2: "13:00-15:00" },
};

Object.keys(result).forEach((key) => {
  const val = result[key];
  result[key] = [];
  Object.keys(val).forEach((k) => {
    result[key].push(val[k]);
  });
});

result

{
friday: []
monday: ['09:00-12:00', '13:00-15:00']
saturday: ['08:00-15:00']
sunday: []
thursday: []
tueday: []
wednesday: ['09:00-12:00', '13:00-15:00']
}

CodePudding user response:

You can try this solution:

const friday = {};
const monday = {1: '09:00-12:00', 2: '13:00-15:00'};
const saturday = {1: '08:00-15:00'};
const sunday = {};
const thursday = {};
const tueday = {};
const wednesday = {1: '09:00-12:00', 2: '13:00-15:00'};

[friday, monday, saturday, sunday, thursday, tueday, wednesday].forEach(weekDay => {
    const result = [];
    
    for (const key in weekDay) {
        result.push(weekDay[key]);
    }
    
    console.log(result);
})

  • Related