I need a function that returns an array of objects but currently, I'm getting an empty array as the return value.
I've got this code:
componentWillMount() {
const data = {
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'
},
]
}
this.setState({
documents: this.getDocuments(data)
})
}
getDocuments = documents => {
const arr = [];
function addDocument(documents, labelKey) {
Object.entries(documents).forEach(([key, val]) => {
if (Array.isArray(val)) {
addDocument(val, key);
} else {
arr.push({ documentID: val.documentID, displayName: `${labelKey || key}: ${val.displayName}` });
}
});
};
return arr;
}
At this point, the code is not executing the addDocument function.
Someone can tell me what I'm doing wrong?
asked Mar 3, 2019 at 23:50
Thore
1,9382 gold badges33 silver badges66 bronze badges
1 Answer 1
Invocation of addDocument added before return statement:
getDocuments = documents => {
const arr = [];
function addDocument(documents, labelKey) {
Object.entries(documents).forEach(([key, val]) => {
if (Array.isArray(val)) {
addDocument(val, key);
} else {
arr.push({ documentID: val.documentID, displayName: `${labelKey || key}: ${val.displayName}` });
}
});
};
addDocument(documents) ;
return arr;
}
addDocument is invoked with only documents parameter because of requirements in Keep original key when re-looping through nested object
Sign up to request clarification or add additional context in comments.
7 Comments
Robin Zigmond
schematically this is indeed what the OP should do - but `labelKey is not defined here, and it's not at all obvious from this small snippet what the OP wants this second parameter to be when calling the function.
chriss
copy paste error, should actually be empty it is used for if(Array
Dave S
This answer could probably be improved by explaining some things. It's not clear at a glance how the code differs from that in the OP, or indeed how/why it answers the question.
Robin Zigmond
That's just an assumption that it "should be empty". I see that the function allows for it to be empty, but presumably the OP will sometimes want it over-ridden. Without knowing the OP's intent this is just guesswork.
chriss
It isn't assumption because i answered it here stackoverflow.com/questions/54974417/…
|
lang-js
addDocument. When are you wanting it to run? I don't know what initial arguments you want it to have, but justaddDocument(..., ...)before the return would suffice.