Published: September 10 2018

Vue.js - Set, Get & Delete Reactive Nested Object Properties

Below are a few simple utility functions for setting, getting and deleting properties of complex / nested objects in Vue.js so the properties are reactive and changes are automatically tracked in the UI. In other words the dynamic object properties are automatically hooked into the Vue.js reactivity system.

I created the functions for a Vue.js + Vuex project I'm currently working on, so they work fine with data stored in Vuex.


Vue.js Set Nested Prop Function

The setProp() function is used to set a deep property on an object and hook it into the Vue.js reactivity system.

Example: to set a new property foo.bar.baz = true on a Vuex state object you would call setProp(state, ['foo', 'bar', 'baz'], true). The function creates any nested properties that don't already exist.

import Vue from 'vue'

function setProp (obj, props, value) {
  const prop = props.shift()
  if (!obj[prop]) {
    Vue.set(obj, prop, {})
  }
  if (!props.length) {
    if (value && typeof value === 'object' && !Array.isArray(value)) {
      obj[prop] = { ...obj[prop], ...value }
    } else {
      obj[prop] = value
    }
    return
  }
  setProp(obj[prop], props, value)
}

export default setProp


Vue.js Get Nested Prop Function

The getProp() function returns the nested property of a javascript object without having to manually check if the property exists first. This is actually a pure vanillaJS function so it can be used outside of Vue.js as well.

Example: to get the property foo.bar.baz from a Vuex state object you would call getProp(state, ['foo', 'bar', 'baz']). If any of the properties in the chain don't exist the function returns undefined.

function getProp (obj, props) {
  const prop = props.shift()
  if (!obj[prop] || !props.length) {
    return obj[prop]
  }
  return getProp(obj[prop], props)
}

export default getProp


Vue.js Delete Nested Prop Function

The deleteProp() function deletes the nested property of a javascript object without having to manually check if the property exists first. It uses Vue.delete() to delete the property so the change is tracked in the Vue.js reactivity system and automatically reflected in any Vue components that use the property.

import Vue from 'vue'

function deleteProp (obj, props) {
  const prop = props.shift()
  if (!obj[prop]) {
    return
  }
  if (!props.length) {
    Vue.delete(obj, prop)
    return
  }
  deleteProp(obj[prop], props)
}

export default deleteProp

 


Need Some Vue Help?

Search fiverr for freelance Vue developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by