J'ai un tableau clé d'objets que l'utilisateur a pendant des jours et leurs horaires pour leur boutique, c'est-à-dire

Utilisateur A -

{
"name" : "shop1",
    "timings" : [ 
        {
            "Monday" : "10am to 7pm"
        }, 
        {
            "Thursday" : "Closed"
        }, 
        {
            "Friday" : "9am to 6pm"
        }, 
        {
            "Sunday" : "Closed"
        }, 
        {
            "Wednesday" : "10am to 7pm"
        }, 
        {
            "Tuesday" : "10am to 7pm"
        }, 
        {
            "Saturday" : "10am to 7pm"
        }
    ]}

Maintenant, je dois afficher ces horaires par jours sur le frontend, c'est-à-dire du lundi au samedi: de 9h à 19h, jeudi, dimanche: fermé

Jusqu'à présent, j'ai essayé de les boucler et de rechercher tous les jours fermés, c'est-à-dire

      function filterByValue(array, string) {
        return array.filter(o =>
            Object.keys(o).some(k => o[k].toLowerCase().includes(string.toLowerCase())));
    }
   let closedDays = filterByValue(element.timings, 'Closed')
console.log("whtt",closedDays); // [{name: 'Lea', country: 'Italy'}]
let res = closedDays.map(x => Object.keys(x)[0]);

Mais pour les journées portes ouvertes, je ne peux trouver aucune solution appropriée qui puisse être utilisée ici. Ce serait d'une grande aide si vous suggérez quelque chose

0
p u 29 août 2020 à 15:34

2 réponses

Meilleure réponse
const timings = [{"Monday": "10am to 7pm"}, {"Thursday": "Closed"}, {"Friday": "9am to 6pm"}, {"Sunday": "Closed"}, {"Wednesday": "10am to 7pm"}, {"Tuesday": "10am to 7pm"}, {"Saturday": "10am to 7pm"}];
const weekDaysInOrder = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

//Step1 little change list of objects
const newTimings = changeTimingsStructure(timings);

let obj = {}
sortTimings(newTimings).forEach(el => {
    if (el.timing in obj) {
        const maxIndex = Math.max(...obj[el.timing].map(el => el.indexOfDay));
        if (maxIndex + 1 < el.indexOfDay && el.timing !== 'Closed') {
            obj = pushToObjectArr(el.timing + '-v2', el, obj);
        } else {
            obj = pushToObjectArr(el.timing, el, obj);
        }
    } else {
        obj = pushToObjectArr(el.timing, el, obj);
    }
})

displayTimings(obj);

function changeTimingsStructure(timings) {
    const newTimings = [];
    timings.forEach(day => {
        const dayName = Object.keys(day)[0]
        const timing = day[dayName];

        newTimings.push({
            day: dayName,
            timing,
            indexOfDay: weekDaysInOrder.findIndex(dayInWeek => dayInWeek === dayName)
        })
    })

    return newTimings;
}

function sortTimings(timings) {
    return timings.sort(((a, b) => a.indexOfDay - b.indexOfDay));
}

function pushToObjectArr(key, el, obj) {
    if (key in obj) {
        obj[key].push(el);
    } else {
        obj[key] = [el]
    }

    return obj
}

function displayTimings(obj) {
    let closedText = '';
    for (const groupOfDays in obj) {
        if (groupOfDays !== 'Closed') {
            if (obj[groupOfDays].length > 1) {
                console.log(`${obj[groupOfDays][0].day} - ${obj[groupOfDays][obj[groupOfDays].length - 1].day}: ${groupOfDays}`);
            } else {
                console.log(`${obj[groupOfDays][0].day}: ${obj[groupOfDays][0].timing}`);
            }
        } else {
            closedText = `${obj[groupOfDays].map(dayObj => dayObj.day).join(', ')}: Closed`;
        }
    }
    console.log(closedText);
}

Essayez ceci, résultat final: entrez la description de l'image ici

1
Piotr Stefański 31 août 2020 à 06:39

Ici, j'ai créé cet utilitaire afin de formater l'entrée selon votre sortie attendue.

let data = {name:'shop1',timings:[{Monday:'10am to 7pm'},{Thursday:'Closed'},{Friday:'9am to 6pm'},{Sunday:'Closed'},{Wednesday:'10am to 7pm'},{Tuesday:'10am to 7pm'},{Saturday:'10am to 7pm'}]};

const formatData = data => {
  return data.reduce(
    (result, d) => {
      const value = Object.values(d)[0];
      const key = Object.keys(d)[0];
      if (value === 'Closed') {
        result.closed.days.push(key);
        if (!result.closed.values) {
          result.closed.value = value;
        }
      } else {
        result.open.days.push(key);
        result.open.timings.push(value);
      }

      return result;
    },
    {
      closed: { days: [], value: '' },
      open: { days: [], timings: [] },
    }
  );
};

const formattedData = formatData(data.timings);

const formatTimings = timings => {
  const formattedTimings= timings.reduce((result, time) => {
    const times = time
        .split('to')
        .map(t => parseInt(t.replace(/\D+/g, '')))
        .filter(Boolean);
        result.from.push(times[0]);
        result.to.push(times[1]);

        return result
  }, {from :[], to: []});

return `${Math.min(...formattedTimings.from)}am to ${Math.max(...formattedTimings.to)}pm`
};

const openDaysTimings = formatTimings(formattedData.open.timings);

const displayTimings = (days, time) => {
  return `${days.join(", ")}: ${time}`
}


console.log(displayTimings(formattedData.closed.days, formattedData.closed.value));
console.log(displayTimings(formattedData.open.days, openDaysTimings));
0
Nithish 29 août 2020 à 13:44