0

I have an array called Cars. How do I get from this:

[
    {
        "id": 1,
        "type": "Car",
        "maxPerson": 4,
    },
    {
        "id": 2,
        "type": "Car",
        "maxPerson": 5,
    }
]

to this.

[
    {
        "id": 1,
        "type": "Car",
        "maxPerson": 4,
        "owner": {
            "username": "jsmith",
            "firstname": "Joe",
            "lastname": "Smith"
        }
    },
    {
        "id": 2,
        "type": "Car",
        "maxPerson": 5,
    }
]

Assuming I know the index of the item. I have tried:

const newOwner = {owner: {username: "jsmith", firstname: "Joe", "lastname": "Smith"};
Cars[index].push(newOwner)

but get:

Cars[index].push is not a function
RGriffiths
  • 5,722
  • 18
  • 72
  • 120

2 Answers2

4

Cars[index] is the object, so Array.push() doesn't work.

Cars[index] = { ...Cars[index], ...newOwner }
wangdev87
  • 8,611
  • 3
  • 8
  • 31
3

Cars[index] is not an array, but an object, so it does not have a function push.

Just assign the owner property (if it does not exist yet, it will be added) of the object

Cars[index].owner = {username: "jsmith", firstname: "Joe", "lastname": "Smith"}.
derpirscher
  • 14,418
  • 3
  • 18
  • 35