Tengo una serie de widgets que contienen varios objetos. Cada objeto contiene una matriz llamada cards que contiene un solo objeto. Necesito ayuda para extraer todos los objetos de las cards y crear una nueva matriz de cards que contenga todas las tarjetas como elementos.
{ "widgets" : [ { "type": "Grid", "cards": [ { "data": {}, "layout": 1 } ] }, { "type": "Grid", "cards": [ { "data": {}, "layout": 1 } ] } ] }como quiero es
{ "widgets": [ { "type": "Grid", "cards": [ { "data": {}, "layout": 1 }, { "data": {}, "layout": 1 } ] } ] }Puede recorrer el origen del objeto original y extraer sus cards en una nueva allCards orig
const allCards = []; for (let widget of orig.widgets) { allCards.push(widget.cards[0]); }Luego puedes construir un nuevo objeto con estas cartas extraídas.
Dado su requerimiento, lo siguiente podría funcionar.
let x = { "widgets" : [ { "type": "Grid", "cards": [ { "data": {}, "layout": 1 } ] }, { "type": "Grid", "cards": [ { "data": {}, "layout": 1 } ] } ] } let y = {"widgets": [{...x.widgets[0], "cards":[]}]}; x.widgets.forEach(el => y.widgets[0].cards.push(...[].concat(el.cards)));Puedes probar este código que tiene en cuenta el tipo de cada widget:
object = { "widgets" : [ { "type": "Grid", "cards": [ { "data": {}, "layout": 1 } ] }, { "type": "Grid", "cards": [ { "data": {}, "layout": 1 } ] }, { "type": "Table", "cards": [ { "data": {}, "layout": 1 } ] }, { "type": "Grid", "cards": [ { "data": {}, "layout": 1 } ] } ] } new_object = {"widgets" : []} for (let i=0; i < object["widgets"].length; i++) { exist = false for (let j=0; j < new_object["widgets"].length; j++) { if (new_object["widgets"][j]["type"] === object["widgets"][i]["type"]){ exist = true new_object["widgets"][j]["cards"].push(object["widgets"][i]["cards"][0]) } } if (exist === false){ new_object["widgets"].push(object["widgets"][i]) } } console.log(new_object)