Reputation: 51
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 ))
Upvotes: 1
Views: 116
Reputation: 664559
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
);
Upvotes: 2
Reputation: 30056
Try out using item
const tempArray = arr.map((item, i) => {
if (item.name === obj.name) {
return obj
} else {
return item
}
})
I think you can even write it as
const tempArray = arr.map((item, i) => {
return (item.name === obj.name ? obj : item)
})
Upvotes: 1