Skip to content

How to Use v-model for Nested Properties? #12432

Discussion options

You must be logged in to vote

The problem is that your code effectively does this:

myObject['foo.bar']

which Javascript doesn't understand. You can only access properties that are present directly on the object with the bracket synax.

To make it work, you could write getter/setter functions for nested properties.
Here is a quick implementation (can probably be written better):

function getNested(object: Record<string, any>, path: string) {
  let result = object;
  for (const propertyName of path.split('.')) {
    if (!propertyName || !(propertyName in result)) {
      return undefined;
    }
    result = result[propertyName];
    if (!result || typeof result !== 'object') {
      break;
    }
  }
  return result;
}

f…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@hasan-ozbey
Comment options

@hubdidub
Comment options

Answer selected by hasan-ozbey
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants