我需要一个返回对象数组的函数,但目前,我得到一个空数组作为返回值。
我有这个代码:
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;
}
此时,代码并未执行 addDocument
函数。
有人可以告诉我我做错了什么吗?
最佳答案
调用在 return 语句之前添加的 addDocument:
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 Keep original key when re-looping through nested object
关于javascript - 函数内的函数没有被执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54974990/