Parsing Included Associations from JSON API response - Rails API, AMS, Vue.js SPA

C. *_*ood 5 javascript json ruby-on-rails active-model-serializers vue.js

I have some data that in a tree/hierarchal model for (climbing) Areas, such that they relate via parent and child areas.

Using the JSON API adapter with my Active Model Serializer,

class AreaSerializer < ActiveModel::Serializer
  attributes :id, :name, :description, :location, :slug
  belongs_to :user
  belongs_to :parent
  has_many :children
end
Run Code Online (Sandbox Code Playgroud)

I can return the Area with the parent and children included in my controller:

class AreasController < ApplicationController

  ...

  def show
    area = Area.friendly.find(params[:id])
    render json: area, include: [:children, :parent]
  end
end
Run Code Online (Sandbox Code Playgroud)

and return exactly what's expected: The JSON response that has Area data, a relationships object that identifies a user_id/type, parent_id/type, children_id/type. This is all being sent to a mutation in a Vuex store for a Vue SPA.

The problem is that everything is mixed up in the included member of the response. I ultimately want easy access to the parent "slug" and store an array of children separately.

Yes, the response has the children and parent in there, but they are all of the same type: "areas", and all together in one array. There must be some reasonable way to parse this data in javascript, such that I can compare the parent: data { id: "5" } in the relationships member of the response to the id of one of the included array members

I understand that I can make this easier if I drop the JSON API spec and just use the default serializer, which will give me parent and children attributes directly in the response data.

Is there some way to parse these related objects in javascript into clearly defined arrays/objects of their own? Maybe I should drop the JSON API specs for this one and just control my data output directly from the server?

I hope that makes sense; someone must have run into this before, but I couldn't find any examples...

plc*_*sta 0

您可以手动解析响应对象:

// User response from server:

const user = {
  "id": "1",
  "type": "users",
  "attributes": {
    "name": "John Doe"
  },
  "included": [
    {
      "id": "2",
      "type": "roles",
      "attributes": {
        "name": "Admin"
      }
    }
  ]
};

// Manually parsing a User response object:
user.id; // 1
user.attributes.name; // John Doe
user.included.filter(obj => obj.type === 'roles')[0].attributes.name; // Admin
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用 JSONAPI Suite:https://jsonapi-suite.github.io/jsonapi_suite/js/home