W
W
WAYNEDEV2021-09-28 13:11:05
Vue.js
WAYNEDEV, 2021-09-28 13:11:05

How to change nested property via chaining in vue?

Hello!

There is an object:

const obj = {
  a: '',
  b: {
    value: ''
  }
}

const obj2 = [
  { model: 'a' } 
  { model: 'b.value' }
]


I need to be able to change in a similar type:

<p v-for="item in obj 2" v-model="obj[model]">

The structure of objects, unfortunately, cannot be changed, from there the question is - how can I get to nested properties in a similar type?

I would be very grateful for your help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-09-28
@WAYNEDEV

computed: {
  model() {
    return new Proxy(Object.fromEntries(this.obj2.map(n => [ n.model, null ])), {
      get: (target, prop) => typeof prop === 'string'
        ? prop.split('.').reduce((p, c) => p?.[c], this.obj)
        : target[prop],
      set: (target, prop, value) => {
        const keys = prop.split('.');
        const key = keys.pop();
        const obj = keys.reduce((p, c) => (!p.hasOwnProperty(c) && this.$set(p, c, {}), p[c]), this.obj);
        this.$set(obj, key, value);
        return true;
      },
    });
  },
},

<div v-for="(v, k) in model">
  <input v-model="model[k]">
</div>

https://jsfiddle.net/34brtvok/
Or, if non-existent paths should not be processed, you can do it simpler:
computed: {
  model() {
    return this.obj2.map(n => {
      const keys = n.model.split('.');
      const key = keys.pop();
      const obj = keys.reduce((p, c) => p?.[c], this.obj);

      return obj && { obj, key };
    }).filter(Boolean);
  },
},

<div v-for="n in model">
  <input v-model="n.obj[n.key]">
</div>

https://jsfiddle.net/34brtvok/1/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question