I got an object array which looks like this:
const items = [
{_id: "Tk2dc3fq99qZ7YdQQ", parent: "Dn59y87PGhkJXpaiZ", content: "one", context: "default"}
{_id: "uK4MYJJGa6ra9e99v", parent: "Dn59y87PGhkJXpaiZ", content: "two", context: "default"}
]
Note: items is readonly as it comes from prop in a react component
And I want to update the content by a given object like this:
const changeThis = { _id: "uK4MYJJGa6ra9e99v", context: "info" }
So the object with the matching ID should get 'info' as new context value while keeping all other elements:
[
{_id: "Tk2dc3fq99qZ7YdQQ", parent: "Dn59y87PGhkJXpaiZ", content: "one", context: "default"}
{_id: "uK4MYJJGa6ra9e99v", parent: "Dn59y87PGhkJXpaiZ", content: "two", context: "info"}
]
Another example
And...
const changeThis = { _id: "uK4MYJJGa6ra9e99v", context: "info", content: "new" }
...should change context and content of the matching object:
[
{_id: "Tk2dc3fq99qZ7YdQQ", parent: "Dn59y87PGhkJXpaiZ", content: "one", context: "default"}
{_id: "uK4MYJJGa6ra9e99v", parent: "Dn59y87PGhkJXpaiZ", content: "new", context: "info"}
]
My attempt
So first of all I would use map() to iterate throught the array, but how do I update all other fields using changeThis-object?
I tried to use assign() and keys() and I tried to ignore the _id-key:
items.map((item, index) => {
if (item._id === changeThis._id) {
Object.assign(
{},
...Object.keys(item).map(k => (
{
[k]: changeThis.indexOf(k) > -1 && k !== '_id'
? changeThis[k]
: item[k]
}
))
}
});
if (..) Object.assign(item, changeThis)?