Guven8 Guven8 - 4 months ago 15
Javascript Question

ES6 implementation of this function?

This function loops through an array of objects, and takes an object as a second parameter.

It will loop through the array of objects replacing it with the object passed in as the second argument if the

firstname
value matches.

I am sure there is a better way of implementing this function using ES6 spread operator but I'm having trouble implementing it.

const foo = (arr, obj) => {
const tempArray = arr.map((item, i) => {
if ( arr[i].name === obj.name ) {
return obj
} else {
return arr[i]
}
})
return tempArray
}

const arrOfObjx = [
{
"name": "Joe",
"favMovie": "Rambo"
},
{
"name": "Jane",
"favMovie": "The Matrix"
},
{
"name": "John",
"favMovie": "Star Wars"
}
]

const newJoe = {
"name": "Joe",
"favMovie": "ROCKY"
}

console.log(foo(arrOfObjx, newJoe ))

Answer

No, there is no use case for the spread operator here. The simplifications to make are in dropping the tempArray variable and in using item instead of arr[i]:

function foo(arr, obj) {
  return arr.map((item, i) => {
    if ( item.name === obj.name ) {
      return obj
    } else {
      return item
    }
  });
}

which you can further shorten to

const foo = (arr, obj) =>
  arr.map(item =>
    item.name === obj.name ? obj : item
  );
Comments