0

I need to develop a function whereby a type property gets appended to an array if it doesn't exist.

So the key will be of type and it should have a value of "dog".

Can someone kindly point out how I can iterate over the array to check if the key "type" exists and also provide guidance on how to append {type:"dog"} to the inner array if it doesn't exist. I tried animalArray[0][1]={type:"dog"} but it doesnt seem to work.

A typical array of animals will look like this:

labelTheDogs(
 [
  {name: 'Obi'}, 
  {name: 'Felix', type: 'cat'}
 ]
)
// should return [
 {name: 'Obi', type: 'dog'}, 
 {name: 'Felix', type: 'cat'}
]
Hazza
  • 1
  • 2

2 Answers2

0

This is not a nested array

function labelTheDogs(dogs) {
  dogs.forEach(dog => {
    if (!dog.type) {
      dog.type = 'dog'
    }
  })
return dogs
}

const dogs = labelTheDogs(
  [{
      name: 'Obi'
    },
    {
      name: 'Felix',
      type: 'cat'
    }
  ]
)

console.log(dogs)
Konrad
  • 21,590
  • 4
  • 28
  • 64
-1

you can use the map function to do that

const newArray = yourArray.map((element) => {
  if(!element.type){
    element.type = "dog";
  }else {
    return element
  }
})
  • Thanks can you please explain line by line what your code is doing? I am new to javascript and don't really understand the => notation – Hazza Aug 07 '22 at 22:03
  • we use The "=>" notation for arrow functions it's just a new way to declare functions. What I simply did is just iterate over the array and check if the type doesn't exist then give it a value. Note that the map function returns a new array that's why I stored the result in a new variable. – Med El Mobarik Aug 07 '22 at 22:09