Tips for utilizing a dot-separated string as the object path for the v-model directive in Vue

I am working with a data record

record: {
  address: {
   city: ""
  }
}

There is an array of objects that describe fields

fields: [ 
  {
    name: "address.city"
    ...
  }
]

My objective is to generate a form dynamically

    <b-field
      v-for="field in fields"
      :key="field.name"
      :label="field.label"
    >
      <b-input v-model="record[field.name]" />
    </b-field>

I need to access object items using keys like address.name.

Although I understand that I should use record[address][city] for the v-model, how can I achieve this from a dot-delimited string?

Is there a way to make it work?

Answer №1

function accessNestedObject(path, obj) {
  const [currentKey, ...remainingKeys] = path.split('.');
  return remainingKeys.length === 0
    ? obj[currentKey]
    : accessNestedObject(remainingKeys.join('.'), obj[currentKey]);
}

document.write(accessNestedObject('x.y.z.w', { x: { y: { z: { w: 'world' } } } }))
CORRECTION perhaps a solution like this. quite hacky though

function unflattenObject(obj) {
  const result = {};
  Object.entries(obj).forEach(([key, value]) => {
    const [firstKey, secondKey] = key.split('.');
    result[firstKey] ||= {};
    result[firstKey][secondKey] = value;
  });
  return result;
}

new Vue({
  el: "#app",
  data: {
    flatRecord: {"personal.firstName": '', "personal.lastName": ''},
    fields: [ 
      { name: "personal.firstName", label: 'First Name' },
      { name: "personal.lastName", label: 'Last Name' }
    ]
  },
  computed: {
    record: ({ flatRecord }) => unflattenObject(flatRecord),
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="{name, label} in fields" :key="name">
     <label>{{ label }}</label><input v-model="flatRecord[name]" /> 
     <br>
  </div>
  <hr>Value of record = {{ record }}
</div>

Answer №2

Instead of using v-model, I opted for :value and @input. I also utilized lodash's get and set

      <b-input
        :value="get(data, field.name)"
        @input="set(data, field.name, $event)"
      />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting ng-click on a custom element directive in Angular 1.x: A guide

Within this code, I have assigned ng-click to a custom element directive with the expectation that clicking the rendered text would trigger an alert saying "Worked from directive!" However, the functionality does not seem to be working as intended. Althou ...

Limiting the size of image uploads in AWS S3

Currently, I am attempting to go through the steps outlined in this repo, which involves utilizing nextjs and AWS S3 for image uploading. However, one thing that is puzzling me is the limitation of 1MB on image sizes. I'm curious as to why this restri ...

Is it possible that MapBoxGL installation with Expo doesn't function properly for web?

I have been working on building an app featuring a map using the MapBoxGL library in Expo. I followed the installation instructions provided by the library, which can be found here. After completing the installation, I proceeded to write the code below to ...

Paste a URL into the input field to view it on the current page

As someone new to HTML, I am in search of a code snippet that will allow users to input a URL in a text box and then be redirected to that URL after clicking on a button. The ideal solution for me would be a straightforward HTML code. I attempted using t ...

Ensuring Typescript returns the accurate type depending on given parameters

i am working with a code example that looks like the following interface BaseQuestionType { label?: string } export type RadioQuestionType = BaseQuestionType & { radio: boolean } export type TextQuestionType = BaseQuestionType & { text: strin ...

Is there a way to import cookies from different browsers into an asp.net application?

After logging into my Facebook account and saving my username/password on Firefox, I am curious about how I can access it from ASP.NET. ...

Dynamic Text Labels in Treemap Visualizations with Echarts

Is it possible to adjust the text size dynamically based on the size of a box in a treemap label? I haven't been able to find a way to do this in the documentation without hardcoding it. Click here for more information label: { fontSize: 16 ...

How can resolvers in GraphQL optimize data fetching based on necessity?

I am working with two unique GraphQL types: type Author { id: String! name: String! } type Book { id: String! author: Author! name: String! } Within my database structure, there exists a foreign key inside the books table: table authors (pseu ...

Is there a way to compress the selected item in arrays in react native?

I am facing an issue with my list of cards. When I press on any card, I want to increase the height of that specific card. I tried using layoutAnimation to handle this case because I encountered an error while trying to setNativeDrive "height" with the Ani ...

Tips for monitoring transactions/events on a particular wallet with ethers.js?

Is there a method to monitor all transactions labeled as "mint" occurring on a designated wallet using ethers.js? While I am aware of the option to establish a filter for tracking a particular event signature, my aim is to keep tabs on all "mint" events, e ...

Customize v-text-field label styling using Vuefity translate

Looking to localize the text displayed on v-text-field and vuetify-google-autocomplete components in Vuetify. Here's a snippet of the code: <template>(...) <v-text-field label="$t('common.nameLabel')" v-model="registerName" r ...

The resizing issue of Textarea during transitions

Whenever I add the transition property to a textarea, it automatically affects the resizing function of the textarea. Is it possible to disable the transition only when resizing the textarea, but not for the textarea itself? <textarea name="" id="" cla ...

magnific popup: trigger the display by clicking on an element other than the image

A recent request from the client calls for the image caption to cover the thumbnail fully when hovered over. To meet this requirement, I now need to enable clicking on the caption to open Magnific Popup rather than using the <a> tag. Here is what I h ...

Exploring the Dev Tools Console feature in Excel for Windows

I have developed an Excel add-in using AngularJS. I utilize <div ng-show="isLoggedIn">...</div> and <div ng-show="!isLoggedIn">...</div> to manage different content based on the value of $scope.isLoggedIn. While it functions well i ...

How to add a jQuery function to a Rails 3 if statement?

I followed a Rails 3 tutorial on creating a multi-step form which you can check out here. Additionally, I incorporated Stripe payment functionality in my app using another railscast found here. Within my application, the payment form is hidden using jQuer ...

Module 'esprima' not found

I am currently working on developing an Abstract Syntax Tree program in JavaScript using Jet brains IDE. I have encountered an issue when running the program, receiving the error message Cannot find module esprima. The settings for nodejs seem to be corr ...

Having trouble with filtering an array using the some() method of another array?

When utilizing the code below, my goal is to filter the first array by checking if the item's id exists in the second array. However, I am encountering an issue where the result is coming back empty. dialogRef.afterClosed().subscribe((airlines: Airli ...

Nuxt js is throwing an error stating that it is unable to locate the pages directory

I have made changes to the folder structure of my Nuxt.js project. I am encountering an issue: Error - Couldn't find a pages directory in D:\sample. How can I access the pages? .nuxt, app, node_modules, server, .eslintrc, package, package-lock ...

When utilizing the dojox.grid.enhanceGrid function to delete a row, the deletion will be reflected on the server side but

I have a grid called unitsGrid that is functioning correctly. I am able to add and delete rows, but the issue arises when I try to delete rows - they do not disappear from my unitsGrid. I have spent hours trying to debug the code but I cannot seem to fin ...

Tips for performing calculations using autopostback without experiencing any distracting screen flicker

Whenever a user selects a number from the dropdownlist on my web form, there is an autopostback that triggers the code below to calculate the sum of the numbers. However, with each recalculation/autopostback, there is an annoying flicker on the screen. Sc ...