Quiero iterar sobre un objeto en Javascript y crear un archivo CSV a partir de sus objetos internos.
const list = { "right": { "label": "Right", "items": ["Jack", "Dough"] }, "wrong": { "label": "Wrong", "items": ["Rain", "Over"] }, "nope": { "label": "Nope", "items": ["No", "Way"] } }; const downLoadCsv = (list) => { let csvContent = ''; Object.keys(statusM).forEach((obj) => { console.log(obj); //do something like obj.items and iterate over internal object - items //but typeof obj is string here }); const anchorEle = document.createElement('a'); anchorEle.href = `data:text/csv;charset=utf-8,${encodeURI(csvContent)}`; anchorEle.target = '_blank'; anchorEle.download = `${key}.csv`; anchorEle.click(); }; Traté de iterar sobre obj pero descubrí que el tipo de typeof obj es una cadena. Más bien esperaba un objeto como el siguiente: -
{ "label": "Right", "items": ["Jack", "Dough"] },Estoy esperando una salida como esta: -
Jack, Right Dough, Right Rain, Wrong Over, Wrong No, Nope Way, Nope¿Puede ayudarme alguien, por favor?
[ ['Jack', 'Right'], ['Dough', 'Right'], ] se logró a través de esto: Object.values(list).map(i => i.items.map(j => [j, i.label])).flat()
después de eso, agregué un método adicional a toCsv para formatear, para permitir la línea de ruptura
const list = { "right": { "label": "Right", "items": ["Jack", "Dough"] }, "wrong": { "label": "Wrong", "items": ["Rain", "Over"] }, "nope": { "label": "Nope", "items": ["No", "Way"] } }; const downLoadCsv = (list) => { let csvContent = toCsv(Object.values(list).map(i => i.items.map(j => [j, i.label])).flat()); const anchorEle = document.createElement('a'); anchorEle.href = `data:text/csv;charset=utf-8,${encodeURI(csvContent)}`; anchorEle.target = '_blank'; anchorEle.download = `test.csv`; anchorEle.click(); }; function toCsv(arr){ return arr.reduce(function(csvString, row){ csvString += row.join(',') ; csvString += "\r\n"; //";";//"\n"; return csvString; }, ''); } downLoadCsv(list)aquí, debe poner valores en lugar de la clave, pero aquí, tengo una ocultación no relacionada porque desconozco ese código.
const list = { "right": { "label": "Right", "items": ["Jack", "Dough"] }, "wrong": { "label": "Wrong", "items": ["Rain", "Over"] }, "nope": { "label": "Nope", "items": ["No", "Way"] } }; const downLoadCsv = (list) => { let csvContent = ''; Object.values(list).forEach((obj) => { console.log(obj); //do something like obj.items and iterate over internal object - items //but typeof obj is string here }); /* const anchorEle = document.createElement('a'); anchorEle.href = `data:text/csv;charset=utf-8,${encodeURI(csvContent)}`; anchorEle.target = '_blank'; anchorEle.download = `${key}.csv`; anchorEle.click(); */ }; downLoadCsv(list)