[Vuejs]-How to lower levels in json?

0👍

If I understand your question, you want to replace your roles array-of-objects to an array which holds only roles.name field.

In this case you can use flatMap method from lodash library.
Assume that your JSON is assigned into a variable called rolesJson, it will look like that:

let rolesJson = {
  "id_role": 2,
  "name": "Prova",
  "email": "prova@prova.com",
  "email_verified_at": null,
  "created_at": "2021-03-01T09:39:42.000000Z",
  "updated_at": "2021-03-01T09:39:42.000000Z",
  "roles": [
    {
      "id": 2,
      "name": "infomanager",
      "guard_name": "web",
      "created_at": "2021-03-01T09:39:42.000000Z",
      "updated_at": "2021-03-01T09:39:42.000000Z",
      "pivot": {
        "model_id": 4,
        "role_id": 2,
        "model_type": "App\\Models\\User"
      }
    }
  ]
};

// create a new attribute with the flatted roles array 
rolesJson.flatted_roles = _.flatMap(rolesJson.roles, el => {
    return el.name;
});

// remove the original roles array
delete rolesJson.roles;

Leave a comment