Estoy alterando los datos de un objeto usando una función .map.

El objeto original cuyos valores estoy tratando de cambiar, pierde su primera línea, lo que me arruina el formato. Creo que es solo la primera línea que pierdo, porque no está incluida de alguna manera en mi función.

El objeto:

graphData = {

"name": "Annual meetings",
  "engagementAreas": [{
    "id": "1",
    "engagementTypes": [{
        "name": "forestry",
        "engagements": []
      },
      {
        "name": "houses",
        "engagements": [{
          "name": "engagement1",
          "members": [{
              "id": "e334", "account": {
                  "id": "eefe" 
              },
            "position": {
              "id": "3434",
              "positionTitle": "Manager"
            }
          }]
        }]
      },
 {
  "name": "landscaping",
  "engagements": [{
    "name": "engagement1343",
    "members": [{
      "position": {
        "id": "4545",
        "positionTitle": "Senior Manager"

      }
      }]
     }]
    }
   ]
},

{
"name": "community days",
    "engagementTypes": [{
        "name": "skyscraping",
        "engagements": []
      },
      {
        "name": "tennis",
        "engagements": [{
          "name": "engagement346",
          "members": [{
              "id": "34", "account": {
                  "id": "3546" 
              },
            "position": {
              "id": "3999434",
              "positionTitle": "Ultime Manager"
            }
          }]
        }]
      },
 {
  "name": "Juicing",
  "engagements": [{
    "name": "347343",
    "members": [{
        "id": "4546", "account": {
            "id": "3545"
        },
      "position": {
        "id": "35006",
        "positionTitle": "Senior Ultimate Manager"

      }
    }]
}]
 }]
}]
}

Esta es la función que uso para alterar los campos de datos (positionTitle)

   const a = realGraphData.engagementAreas.map((el, i) => {
        el.engagementTypes.forEach((et) => {
           et.engagements.forEach((eg) => {
              eg.members.forEach((mem) => {
                 mem.position.positionTitle = 'abc'

              });
           });
        });

        return el;
      })

Mi resultado esperado debería ser:

{
    "name": "Annual meetings",
    "engagementAreas": [{
        "id": "1",
        "engagementTypes": [{
            "name": "forestry",
            "engagements": []
        }, {
            "name": "houses",
            "engagements": [{
                "name": "engagement1",
                "members": [{
                    "id": "e334",
                    "account": {
                        "id": "eefe"
                    },
                    "position": {
                        "id": "3434",
                        "positionTitle": "abc"
                    }
                }]
            }]
        }, {
            "name": "landscaping",
            "engagements": [{
                "name": "engagement1343",
                "members": [{
                    "position": {
                        "id": "4545",
                        "positionTitle": "abc"
                    }
                }]
            }]
        }]
    }, {
        "name": "community days",
        "engagementTypes": [{
            "name": "skyscraping",
            "engagements": []
        }, {
            "name": "tennis",
            "engagements": [{
                "name": "engagement346",
                "members": [{
                    "id": "34",
                    "account": {
                        "id": "3546"
                    },
                    "position": {
                        "id": "3999434",
                        "positionTitle": "abc"
                    }
                }]
            }]
        }, {
            "name": "Juicing",
            "engagements": [{
                "name": "347343",
                "members": [{
                    "id": "4546",
                    "account": {
                        "id": "3545"
                    },
                    "position": {
                        "id": "35006",
                        "positionTitle": "abc"
                    }
                }]
            }]
        }]
    }]
}

En cambio, es lo mismo que el anterior, solo que sin la línea inicial,

"name": "Annual meetings",
  "engagementAreas":

Así es:

[{
    "id": "1",
    "engagementTypes": [{
        "name": "forestry",
        "engagements": []
    }, {
        "name": "houses",
        "engagements": [{
            "name": "engagement1",
            "members": [{
                "id": "e334",
                "account": {
                    "id": "eefe"
                },
                "position": {
                    "id": "3434",
                    "positionTitle": "abc"
                }
            }]
        }]
    }, {
        "name": "landscaping",
        "engagements": [{
            "name": "engagement1343",
            "members": [{
                "position": {
                    "id": "4545",
                    "positionTitle": "abc"
                }
            }]
        }]
    }]
}, {
    "name": "community days",
    "engagementTypes": [{
        "name": "skyscraping",
        "engagements": []
    }, {
        "name": "tennis",
        "engagements": [{
            "name": "engagement346",
            "members": [{
                "id": "34",
                "account": {
                    "id": "3546"
                },
                "position": {
                    "id": "3999434",
                    "positionTitle": "abc"
                }
            }]
        }]
    }, {
        "name": "Juicing",
        "engagements": [{
            "name": "347343",
            "members": [{
                "id": "4546",
                "account": {
                    "id": "3545"
                },
                "position": {
                    "id": "35006",
                    "positionTitle": "abc"
                }
            }]
        }]
    }]
}]
1
Sparlarva 10 sep. 2018 a las 15:09

3 respuestas

La mejor respuesta

Puede usar Object.assign o el operador de propagación para lograr una copia completa con las propiedades actualizadas, un ejemplo de este código sería el siguiente

const updatedGraphTable = { ...graphData,
  engagementAreas: graphData.engagementAreas.map(area => ({ ...area,
    engagementTypes: area.engagementTypes.map(type => ({ ...type,
        engagements: type.engagements.map(engagement => ({ ...engagement,
          members: engagement.members.map(member => ({ ...member,
            position: { ...member.position,
              positionTitle: 'abc'
            }
          }))
        }))}))
    }))
  };

Esto no hace que el código sea muy legible, pero sería una conversión de una línea. El operador de propagación copiará todas las propiedades del objeto y luego sobrescribiremos las propiedades existentes redefiniéndolas.

const graphData = {
  "name": "Annual meetings",
  "engagementAreas": [{
      "id": "1",
      "engagementTypes": [{
          "name": "forestry",
          "engagements": []
        },
        {
          "name": "houses",
          "engagements": [{
            "name": "engagement1",
            "members": [{
              "id": "e334",
              "account": {
                "id": "eefe"
              },
              "position": {
                "id": "3434",
                "positionTitle": "Manager"
              }
            }]
          }]
        },
        {
          "name": "landscaping",
          "engagements": [{
            "name": "engagement1343",
            "members": [{
              "position": {
                "id": "4545",
                "positionTitle": "Senior Manager"

              }
            }]
          }]
        }
      ]
    },

    {
      "name": "community days",
      "engagementTypes": [{
          "name": "skyscraping",
          "engagements": []
        },
        {
          "name": "tennis",
          "engagements": [{
            "name": "engagement346",
            "members": [{
              "id": "34",
              "account": {
                "id": "3546"
              },
              "position": {
                "id": "3999434",
                "positionTitle": "Ultime Manager"
              }
            }]
          }]
        },
        {
          "name": "Juicing",
          "engagements": [{
            "name": "347343",
            "members": [{
              "id": "4546",
              "account": {
                "id": "3545"
              },
              "position": {
                "id": "35006",
                "positionTitle": "Senior Ultimate Manager"

              }
            }]
          }]
        }
      ]
    }
  ]
};

const updatedGraphTable = { ...graphData,
  engagementAreas: graphData.engagementAreas.map(area => ({ ...area,
    engagementTypes: area.engagementTypes.map(type => ({ ...type,
        engagements: type.engagements.map(engagement => ({ ...engagement,
          members: engagement.members.map(member => ({ ...member,
            position: { ...member.position,
              positionTitle: 'abc'
            }
          }))
        }))}))
    }))
  };
  
console.log( updatedGraphTable );
1
Icepickle 10 sep. 2018 a las 12:30

map crea una nueva matriz que es una matriz de entrada transformada. Lo que estás mapeando es realGraphData.engagementAreas para que obtengas una versión transformada.

Editar:

Para este tipo de tareas es mejor usar alguna biblioteca que ayude a manipular objetos como ramda o lodash.

function main() {
  const spec = {
    engagementAreas: [{
      engagementTypes: [{
        engagements: [{
          members: [{
            position: {
              positionTitle: () => "abc"
            }
          }]
        }]
      }]
    }]
  };
  const result = transform(spec, graphData);
  console.log(result);
}


const graphData = {

  "name": "Annual meetings",
  "engagementAreas": [{
      "id": "1",
      "engagementTypes": [{
          "name": "forestry",
          "engagements": []
        },
        {
          "name": "houses",
          "engagements": [{
            "name": "engagement1",
            "members": [{
              "id": "e334",
              "account": {
                "id": "eefe"
              },
              "position": {
                "id": "3434",
                "positionTitle": "Manager"
              }
            }]
          }]
        },
        {
          "name": "landscaping",
          "engagements": [{
            "name": "engagement1343",
            "members": [{
              "position": {
                "id": "4545",
                "positionTitle": "Senior Manager"

              }
            }]
          }]
        }
      ]
    },

    {
      "name": "community days",
      "engagementTypes": [{
          "name": "skyscraping",
          "engagements": []
        },
        {
          "name": "tennis",
          "engagements": [{
            "name": "engagement346",
            "members": [{
              "id": "34",
              "account": {
                "id": "3546"
              },
              "position": {
                "id": "3999434",
                "positionTitle": "Ultime Manager"
              }
            }]
          }]
        },
        {
          "name": "Juicing",
          "engagements": [{
            "name": "347343",
            "members": [{
              "id": "4546",
              "account": {
                "id": "3545"
              },
              "position": {
                "id": "35006",
                "positionTitle": "Senior Ultimate Manager"

              }
            }]
          }]
        }
      ]
    }
  ]
}

const transform = R.curry((spec, objOrArray) => {
  const mapWithIndex = Array.isArray(objOrArray)
    ? R.addIndex(R.map)
    : R.mapObjIndexed;
  return mapWithIndex((value, key) => {
    const fnOrSpec = typeof key === "number" ? spec[0] : spec[key];
    if (fnOrSpec) {
      if (typeof fnOrSpec == "function") {
        return fnOrSpec(value);
      }
      return transform(fnOrSpec, value);
    }
    return value;
  }, objOrArray);
});

main();
<script src="https://unpkg.com/ramda@0.25.0/dist/ramda.min.js"></script>
1
marzelin 10 sep. 2018 a las 13:24

El mapa devuelve una serie de resultados. Lo estás entregando todo dentro de "engagementAreas". En su lugar, intente solo pasar la matriz a su función y establezca la parte "engagementAreas" de su objeto en el valor devuelto

1
Steve Bohmbach 10 sep. 2018 a las 12:17