I am attempting to replace an object's property (a string) with a matching keyed object from another object where the values are also keyed.
For example...
const dataRefs = {
'idkey1': { title: "Key1", /*...etc... */ },
'idkey2': { title: "Key2", /*...etc... */ },
'idkey3': { title: "Key3", /*...etc... */ },
// ...etc...
};
const pages = [
{ title: "A Page", data: 'idkey1' },
// ...etc...
];
With the code below, my goal is to substitute pages[n].data
with the corresponding property in dataRefs
. When looping through the pages using forEach
...
pages.forEach(page => page.data = dataRefs[page.data])
However, after doing this, the page.data
property turns out to be undefined
, despite it should match.
When trying to debug by console output, I observe an odd behavior where the undefined value only appears when the code is added after the output...
// This works perfectly and achieves the desired match.
pages.forEach(page => console.log("%s: ", page.data, dataRefs[page.data]));
// Output:
// idkey1: undefined
// On the other hand, this leads to unexpected results and ends up with "undefined".
pages.forEach(page => {
// using console.log to see what's going on...
console.log("%s: ", page.data, dataRefs[page.data]);
page.data = dataRefs[page.data];
});
// Output:
// [Object object]: undefined
// Trying this alternative, just in case how the DOM inspector
// might be using references, but still the same issue...
pages.forEach(page => {
console.log(page.data + ": ", dataRefs[page.data]);
page.data = dataRefs[page.data];
});
// Output:
// [Object object]: undefined
I have double-checked variable spellings and tried various permutations of the code repeatedly, but it seems that no matter what I attempt, calling page.data = dataRefs[page.data]
does not function as expected. Could this be a complex race-condition or maybe I've been watching too much Matrix lately?
This is being executed within the Component's render()
method.
Using Safari 14.1.2 for reference.