2👍
There are different ways to access your object in Javascript.
var myObj = {
variableOne: {
variableOneA: 'oneA',
variableOneB: 'oneB'
}
variableTwo: {
variableTwoA: 'twoA',
variableTwoB: 'twoB
}
variableThree: {
variableThreeA: 'threeA',
variableThreeB: 'threeB'
}
}
You can use “dot” to access a particular level of your object.
const valueVariableOneA = myObj.variableOne.variableOneA
console.log(valueVariableOneA) // output => "oneA"
You can use the square brackets in replacement of dot. Square brackets are usefull when you want to create an object’s key with dash (eg: “cool-key”)
const valueVariableThreeB = myObj['variableThree']['variableThreeB']
console.log(valueVariableThreeB) // output => "threeB"
You can also use the destructuration to access particular value
// Get value of variableTwoA key
const { variableTwoA } = myObj.variableTwo // first way
const { variableTwo : { variableTwoA } } = myObj // second way
console.log(variableTwoA) // output => "twoA"
Now to add a key to a nested object you can use either dot or square brackets method. Here’s how to add key on the first level.
myObj.variableFour = { variableFourA: 'fourA', variableFourB: 'fourB' }
myObj['variableFour'] = { variableFourA: 'fourA', variableFourB: 'fourB' }
// add key on nested object
myObj.variableOne.variableOneC = 'oneC'
myObj['variableOne']['variableOneC'] = 'oneC'
// you can mix both
myObj['variableOne'].variableOneC = 'oneC'
myObj.variableOne['variableOneC'] = 'oneC'
1👍
Use this code:
myObj.variableOne['someValue'] = 'new value';
- [Vuejs]-Importing services in Vue.js
- [Vuejs]-Vuex. How to render data after it has been received from API before component started
Source:stackexchange.com