Skip to content

Instantly share code, notes, and snippets.

@qborreda
Created May 8, 2017 09:47
Show Gist options
  • Save qborreda/10d5ee4d0d4a97ed7cdff90c9dc59129 to your computer and use it in GitHub Desktop.
Save qborreda/10d5ee4d0d4a97ed7cdff90c9dc59129 to your computer and use it in GitHub Desktop.
Updates key value within an array of objects
const objArr = [
{ letter: 'a', num: 1 },
{ letter: 'b', num: 2 },
{ letter: 'c', num: 3 }
]
const updateObjInArr = (oldArr, searchKey, oldVal, newVal) => {
return oldArr.map(item => {
if (item[searchKey] === oldVal) {
item[searchKey] = newVal
}
return item
})
}
const updatedArr = updateObjInArr(objArr, 'letter', 'c', 'c--updated')
console.log(updatedArr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment