T
T
Tamerlan Godzhiev2018-09-20 11:29:40
Vue.js
Tamerlan Godzhiev, 2018-09-20 11:29:40

How to display the elements of a nested object?

Help with the output of the elements.

I display an object

<ul class="list-group" id="v-for-object">
  <li v-for="value in object" class="list-group-item">{{ value }}</li>
</ul>


But it also contains a nested object:

data: {
        object1: {
            firstName: 'Bruce Lee',
            userName: 'Dragoon',
            email: '[email protected]',
            adress: {
                country: 'China',
                town: 'Gong-kong'
            },
        }

As a result, adress is output like this:
{ "country": "China", "town": "Gong-kong" }

How can I easily print the name of China and Gong-kong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-09-20
@tamerlan676

You can make a method that transforms an object so that there is no nesting:

methods: {
  plainObj(obj) {
    return Object.entries(obj).reduce((acc, [ k, v ]) => {
      if (v instanceof Object) {
        Object.assign(acc, this.plainObj(v));
      } else {
        acc[k] = v;
      }
      return acc;
    }, {});
  }
}

<li v-for="value in plainObj(object)" class="list-group-item">{{ value }}</li>

Or make a recursive component :
Vue.component('list-obj', {
  template: `
<ul class="list-group">
  <li v-for="value in obj" class="list-group-item">
    <list-obj v-if="value instanceof Object" :obj="value"></list-obj>
    <span v-else>{{ value }}</span>
  </li>
</ul>`,
  props: [ 'obj' ]
});

<list-obj :obj="object"></list-obj>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question