1

So I am using a JSON object that looks something like this:

data: [
  {
    title: "Post Title One",
    categories: {
      data: [
        {
          id: 1,
          name: "Category Name 1"
        }
      ]
    }
  },
  {
    title: "Post Title Two",
    categories: {
      data: [
        {
          id: 2,
          name: "Category Name 1"
        },
        {
          id: 3,
          name: "Category Name 2"
        }
      ]
    }
  }
]

and I want to grab all the categories for each post and display them using Vue. So what I have currently is:

<div v-for="post in posts">
   <div>{{ post.categories.data }}</div>
</div>

In that {{ post.categories.data }} I am trying to display the category name from the JSON object. When I use what I have above the whole array is displayed in the div. When I try to do something like

{{ post.categories.data.name }} 

or

{{ post.categories.data[0].name }}

I don't display the name of the category. I would really like to display the name of every category a post has, but can't seem to get it to display correctly.

EDIT: Also posts is the data property I am using in VueJS and am setting the JSON object to become that property.

1
  • Did you try "post.categories.data.map(d => d.name).join()" ? This will display all category names together Commented Oct 26, 2018 at 12:27

1 Answer 1

2

You should use map method in conbination with destructuring.

<div v-for="post in posts">
    <div>{{ post.categories.data.map(({name}) => name).join(' ') }}</div>
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

That did the trick, Thanks! I am going to look more into the map method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.