I want something similar to this :
Cars {
"test-01-test" : {
brand: 'anybrand',
color: 'blue,
}
I want Cars as an Object and the id "test-01-test" as an Object too.
So I can read it like that :
console.log(this.cars["test-01-test"].color) //result should be blue
I tried this in my data function
cars : {
id : {
brand : '',
color : '',
}
}
and then in my mounted in I wrote this :
this.cars.id = "test-01-test";
this.cars.id["test-01-test"].color="blue";
console.log(this.cars);
But the console says that :
Cannot set property 'color' of undefined
I want to set-up the color and the like my first exemple, how can I do ?
What I'm trying to do, is the add IDs dynamically. If I do something like this (imagine I ask the users with a modal to insert a new car with a new id):
this.cars[id] = "test-02-test" //test-02-test was given by the user's input
I want to create a new object with the value "test-02-test" and then put the color and the brand so my data looks like this :
Cars {
"test-01-test" : {
brand: 'anybrand',
color: 'blue,
},
"test-02-test" : {
brand: 'anybrand',
color: 'blue,
}
What you did is:
let cars = {
id: {
brand: '',
color: '',
}
};
cars.id = "test-01-test";
console.log(cars);
Instead you should do:
let cars = {
id: {
brand: '',
color: '',
}
};
console.log(cars);
cars.id.color = "blue";
console.log(cars);
or dynamically:
let cars = {
peugeot: {
brand: '',
color: '',
},
citroen: {
brand: '',
color: '',
}
};
let id = 'citroen'
cars[id].color = "blue";
console.log(cars);
You can add a new id like below:
let cars = {
peugeot: {
brand: '',
color: '',
},
citroen: {
brand: '',
color: '',
}
};
let id = 'ford'
cars[id] = {
brand: '',
color: '',
};
console.log(cars);
or with https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
let cars = {
peugeot: {
brand: '',
color: '',
},
citroen: {
brand: '',
color: '',
}
};
cars = {...cars, dodge: {
brand: '',
color: '',
}
}
console.log(cars);
Your ID is a key inside this object
Try:
let cars = {
"test-01-test" : {
brand : 'anybrand',
color : 'blue',
}
}
console.log(cars["test-01-test"].color)
// Output: blue
Because identifier is case sensitive. A function define in global scope, 'this' refer in this function window object, when you access 'this' in function it refer window.cars. So, window.cars is not equal to window.Cars.