I've got a nested object with child objects and arrays. Something like this:
const documents = {
invoice: {
documentID: '_e4564',
displayName: '2019-02-03',
url: 'https://www.urltoinvoice.com'
},
conditions: {
documentID: '_e9365',
displayName: 'Conditions company x',
url: 'https://www.urltoconditions.com'
},
reminders: [
{
documentID: '_e4364',
displayName: 'First reminder',
url: 'https://www.urltofirstreminder.com'
},
{
documentID: '_e0254',
displayName: 'Second reminder',
url: 'https://www.urltosecondreminder.com'
},
]
}
I'm trying to create a new array of objects to use in a select box. The child objects need the same properties but with an updated displayName based on the document type. So, for example, reminder: First reminder .
Currently, this is my code:
const newArray = [];
this.addDocumentToArray(documents, newArray);
and the addDocumentToArray function:
addDocumentToArray = (documents, arr) => {
Object.entries(documents).forEach(([key, val]) => {
if (Array.isArray(val)) {
this.addDocumentToArray(val, arr);
} else {
arr.push({ documentID: val.documentID, displayName: `${key}: ${val.displayName}` });
}
});
}
The output at this point is an array that looks like this:
0: {documentID: "_e4564", displayName: "invoice: 2019-02-03"}
1: {documentID: "_e9365", displayName: "conditions: Conditions company x"}
2: {documentID: "_e4364", displayName: "0: First reminder"}
3: {documentID: "_e0254", displayName: "1: Second reminder"}
Almost ok but the key of the reminders is 0
and 1
. How can I get reminder
(or reminders) as key?