Last active
October 13, 2022 13:16
-
-
Save trafficinc/b29e5020b5567239ac89d3597e312745 to your computer and use it in GitHub Desktop.
Update JavaScript Object in Collection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let startTime = new Date(); | |
// updating an object in a array/collection | |
let collection = [ | |
{id:3, name:"Item #1",age:32}, | |
{id:4, name:"Item #2",age:33}, | |
{id:5, name:"Item #3",age:34}, | |
{id:6, name:"Item #4",age:35}, | |
{id:7, name:"Item #5",age:36}, | |
{id:8, name:"Item #6",age:47}, | |
]; | |
function assign(o,replace) { | |
Object.keys(o).map(function(key) { | |
if (replace[key] !== undefined) { | |
o[key] = replace[key]; | |
} else { | |
o[key] = o[key]; | |
} | |
}); | |
return o; | |
} | |
function updateObj(collection, id, replacement) { | |
return collection.map(function (o) { | |
return o.id === id ? assign(o,replacement) : o; | |
}); | |
} | |
console.log(collection); | |
let newCollection = updateObj(collection, 6, {name: "Demo Hello"}); | |
console.log(newCollection); | |
let newCollection2 = updateObj(collection, 3, {age: 87}); | |
console.log(newCollection2); | |
console.log('It took ' + new Date() - startTime + ' milliseconds to calculate.'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment