1

I am using Bootstrap-Vue and VueJs and need help with some custom data rendering from multiple data objects and displaying the data into a table. Specifically, I am following this part of the Bootstrap-Vue TABLE docs: https://bootstrap-vue.js.org/docs/components/table#formatter-callback but I am unsure how to apply it to my code.

Here's my scenario:

I have a data API providing 2 different arrays of objects: posts and names

Posts:

    [
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
...snip..
    ]

and Names:

[{"userId":1,"first_name":"Neill","last_name":"Dexter","email":"[email protected]"},
...snip
]

The posts array contains a userId key but no name of the user. The names array contains the userId key and the first_name and last_name of that user.

What I want to do is simply display the full name of the user in my Bootstrap-vue Table component rather than the userId because just showing the userId doesn't make sense.

Here's my attempt (link to editable live code):

<template>
  <div>
    <b-table :items="posts" :fields="fields">
      <!-- A custom formatted column -->
      <template slot="name" slot-scope="data">{{ data.value.userId }}</template>
    </b-table>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      posts: [],
      names: [],
      // key name is the slot name
      fields: [
        { key: "id" },
        { key: "title" },
        { key: "body" },
        { key: "name", label: "Assigned To", formatter: "assignNames" }
      ]
    };
  },
  created() {
    this.getPosts();
    this.getNames();
  },
  methods: {
    getPosts() {
      axios.get("https://jsonplaceholder.typicode.com/posts").then(resp => {
        this.posts = resp.data;
      });
    },
    getNames() {
      axios
        .get("https://my.api.mockaroo.com/users.json?key=f119e0f0")
        .then(resp => {
          this.names = resp.data;
        });
    },
    assignNames() {
      var i;
      for (i = 0; i < this.posts.length; i++) {
        if (this.posts[i].userId !== null) {
          const result = this.names.filter(name => {
            return name.userId === this.posts[i].userId;
          });
          this.posts[i].userId =
            result[0].first_name + " " + result[0].last_name;
        }
      }
    }
  }
};
</script>

Anyone got any tips on how I can show the full name of my users rather than just the userId? Thanks!

1 Answer 1

1
assignNames(id) {
  const user = this.names.find(e => e.userId === id);
  return  user ? `${user.first_name} ${user.last_name}` : 'loading...';
}

... but, obviously, the key has to be userId, as that's the name of the property referenced in post structure:

{ key: "userId", label: "Assigned To", formatter: "assignNames" }

See it here.

Also, you shouldn't name the results from second api names, but users.


Note: In the example I linked I placed the results of users inside a json saved in the project and mocked the api call by a promise getting that json, as your api key exceeded its daily limit and was returning a 500.

Sign up to request clarification or add additional context in comments.

7 Comments

Unfortunately, your users API exceeded its daily limit and returns 500 now. You might want to make a new account, grab the dummy data, save it as json in your project and mock an http request to it. Note the way you're currently handling fetching data, any change in the editor will cause the app to rebuild and refetch.
Thank you so much. I will study this. Quick question...is the find() method safe to use in browsers? I saw it's not compatible with IE11 and earlier.
To use it in IE you'd need its polyfill. Or this one (they might actually be the exact same thing).
If I use vue-cli does it come with the polyfill?
Took me a while, but I got it working with my actual data. Thank you! P.S> I noticed that the table doesn't filter the custom formatter data...I'll have to look into that.
|

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.