I want to add a property/key to array of objects whose value differs based on start index and stop index passed [duplicate]

I want to add a property/key to array of objects whose value differs based on start index and stop index passed.

For eg.
-I want to add the property car:blue at index 0

  • car:red from index 1 to 3
  • car:yellow at index 4 and 5.

so a function setcarColor(color,indexStart,indexEnd)

I have also added what the initial array of objects looks like and what the final one should look like


InitialObj = [{
    "id": "61f28d0679874e6644233cd3",
    "name": "abc"
  },
  {
    "id": "61f28d0679874e6644233cd3",
    "name": "efg"
  },
  {
    " id ": " 61f28d0679874e6644233cd3 ",
    " name ": "hij "
  },
  {
    " id ": " 61f28d0679874e6644233cd3 ",
    " name ": "klm",
  },
  {
    " id ": " 61f28d0679874e6644233cad ",
    " name ": "nop",
  },
  {
    " id ": " 61f28d0679874e6644233cfd ",
    " name ": "qrd",
  }
]

After using passing the values to function,The object will look like below

finalObj = [{
    " id ": " 61f28d0679874e6644233cd3 ",
    " name ": "abc",
    " car ": "blue"
  },
  {
    " id ": " 61f28d0679874e6644233cd3 ",
    " name ": "efg",
    "car": "red"

  },
  {
    "id": "61f28d0679874e6644233cd3",
    "name": "hij",
    "car": "red"

  },
  {
    "id": "61f28d0679874e6644233cd3",
    "name": "klm",
    "car": "red"
  },
  {
    "id": "61f28d0679874e6644233cad",
    "name": "nop",
    "car": "yellow"

  },
  {
    "id": "61f28d0679874e6644233cfd",
    "name": "qrd",
    "car": "yellow"
  }
]