1

I have a JavaScript object customer that looks like this...

Object {
    name: "John Doe",
    age: "26"
}

I want to create a cars section and add some specifics so it looks like this...

Object {
    name: "John Doe",
    age: "26"
    cars:  {
        car1 {
            color: red,
            type: ford
        },
        car2 {
            color: blue,
            type: GMC
        },
        car3 {
            color: white,
            type: toyota
        }
    }
}

I have tried to do this like this...

customer['cars']['car1'] = { color:'white', type:'toyota' }

But this gives me the error...

customer.cars is undefined

Where am I going wrong?

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
jsmitter3
  • 411
  • 1
  • 4
  • 15
  • create `customer.cars = {}` first and then create inner objects =) – halilcakar Apr 13 '21 at 09:17
  • `customer.cars = { car1: { color: 'white', type: 'toyota' } };`, you need to create the containing object, that will be placed in `customer.cars`. You can do this in two steps as well: `customer.cars = {}; customer['cars']['car1'] = { color:'white', type:'toyota' };`. – ASDFGerte Apr 13 '21 at 09:19

3 Answers3

4

Problem

The error msg means that customer.cars has not been declared/assigned.


Solution

There are 2 options:

  1. initialize empty cars object (In case that you want to assign each car)

var customer = {name:"John Doe",age:"26"};

customer.cars = {}; // init empty cars object
customer.cars.car1 = { color:'white', type:'toyota' }; 
customer.cars.car2 = { color:'blue', type:'GMC' }; 

console.log(customer);
  1. assign all cars property directly.

var customer = {name:"John Doe",age:"26"};
customer.cars = {car1:{color:"red",type:"ford"},car2:{color:"blue",type:"GMC"},car3:{color:"white",type:"toyota"}};

console.log(customer);
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
  • Welcome, @jsmitter3 to Stackoverflow. I saw that you forgot to mark the answers as resolved by clicking the tick to help the reader in the future https://stackoverflow.com/help/someone-answers – Nguyễn Văn Phong Apr 16 '21 at 07:36
3

You calling an undefined field cars on a customer record.

Try to define it first:

customer.cars = {}

And only then:

customer.cars.car1 = {...}

You can use [] syntax too:

customer['cars'] = {}
Konstantin
  • 354
  • 2
  • 3
2
const obj =  {
    name: "John Doe",
    age: "26"
}

obj.cars = {car1 : {color: 'white'}}

console.log(obj)

The way you're inserting the object is incorrect. See my example for the correct way to do this.

Kevin.a
  • 4,094
  • 8
  • 46
  • 82