Estoy revisando algunos datos, que estoy extrayendo de algunos sitios web. Actualmente estoy raspando la cabeza.
Este es un ejemplo de la estructura de datos.
const head = { rel_data: [ { rel: "rel", items: [ { type: "type", sizes: "sizes", href: "href" } ] } ] }; Siempre que el rel coincida, quiero insertar los datos en items
$('head link').each(function(index) { if(head?.rel_data[index]?.rel == rel) { head?.rel_data[index]?.items.push({ type: (type !== undefined) ? type : null, sizes: (sizes !== undefined) ? sizes : null, href: (href !== undefined) ? href : null }); } else { head.rel_data.push({ rel: (rel !== undefined) ? rel : null, items: [ { type: (type !== undefined) ? type : null, sizes: (sizes !== undefined) ? sizes : null, href: (href !== undefined) ? href : null } ] }); } })Como esto
rel_data: [ { rel: "icon", items: [ { type: "type", sizes: "sizes", href: "href" }, { type: "type", sizes: "sizes", href: "href" } ] }, { rel: "other-rel-type", items: [...] } ]Pero lo que me sale es esto.
rel_data: [ { rel: "icon", items: [ { type: "type", sizes: "sizes", href: "href" } ] }, { rel: "icon", items: [ { type: "type", sizes: "sizes", href: "href" } ] } ] Si escribo 0 , en lugar de index , funciona con el primer tipo de rel (icon por ejemplo) pero no con el resto?
Una solución simple sería almacenar los datos en un objeto temporal en lugar de una matriz y usar los valores rel como claves.
Luego, cuando haya terminado, use Object.values(tempObject) para obtener la matriz final
Este objeto se vería algo como:
const obj = { "icon": { rel: "icon", items: [{ type: "type", sizes: "sizes", href: "href" } ] }, "other-rel-type": { rel: "other-rel-type", items: [] } }Entonces, una versión simplificada de su ciclo sería algo como:
$('head link').each(function(index) { const rel = this.rel obj[rel] = obj[rel] || { rel, items:[]} obj[rel].items.push({type:..., sizes:...}) });Entonces finalmente :
head.rel_data = Object.values(obj)