javascript - 函数内的函数没有被执行

标签 javascript function

我需要一个返回对象数组的函数,但目前,我得到一个空数组作为返回值。

我有这个代码:

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/

相关文章:

javascript - 覆盖订阅是否会自动取消订阅以前的值?

javascript - 单击时全屏 div

c - 如何只有一些参数到函数 C

C 程序仅接受整数 1-42 到数组中,并且它们不能在函数中重复

JavaScript 函数和事件

c++ - 在 C++ 中管理成员函数执行

javascript - 如何使用数据表在单击按钮时显示带有列数据的确认模态

javascript - Vue.js 输入元素值为空

sql - 选择结果作为用户定义的表参数函数中的参数

javascript - 这个三元组可以安全地处理 JavaScript 中的 undefined 吗?