Javascript 在数组上调用forEach时出错

Javascript 在数组上调用forEach时出错,javascript,node.js,foreach,Javascript,Node.js,Foreach,我在另一个forEach函数中遇到一个forEach问题: results变量包含如下对象: { names: [ 'Someone', 'Someone else' ], emails: [ 'someone@someemail.com' 'something@somemail.com' ] } 我希望它展开所有数组并生成如下数组: [ {term: 'Someone', type: 'n

我在另一个forEach函数中遇到一个forEach问题:

results
变量包含如下对象:

{
    names: [
        'Someone',
        'Someone else'
    ],
    emails: [
        'someone@someemail.com'
        'something@somemail.com'
    ]
}
我希望它展开所有数组并生成如下数组:

[
    {term: 'Someone', type: 'names'},
    ...
]
这是我的密码:

var keys = _.keys(results);

console.log(keys);

var finalResult = [];

keys.forEach( function (key) {

    var arrTerms = results[key];

    console.log(key, arrTerms); //arrTerms prints fine

    arrTerms.forEach(function (term) { //This line throws an exception

        finalResult.push({
            term: term,
            type: key
        });
    });

});
对forEach的嵌套调用引发以下异常:

TypeError: Uncaught error: Cannot call method 'forEach' of undefined
TypeError: Uncaught error: Cannot read property 'length' of undefined
我尝试使用迭代到长度的for循环,但它生成了另一个异常:

TypeError: Uncaught error: Cannot call method 'forEach' of undefined
TypeError: Uncaught error: Cannot read property 'length' of undefined

我认为这里的问题是,您可能会将undefined指定给arrTerms(当results[key]返回undefined时,因为您使用的键不包含在对象中)。尝试这样做:

var keys = _.keys(results);

console.log(keys);

var finalResult = [];

keys.forEach( function (key) {
    if(results[key] != undefined){
     var arrTerms = results[key];

     arrTerms.forEach(function (term) { //This line throws an exception
        console.log(key, arrTerms); //arrTerms prints fine
        finalResult.push({
            term: term,
            type: key
        });
     });
    }
});

试试,
console.log(key,arrTerms,Array.isArray(arrTerms))代码本身对我来说很好(除了数组定义中缺少逗号)。
results
实际上是什么样子的?它将typeOf打印为Object@ZeMoon抱歉,请尝试
Array.isArray
。我编辑了comment@thefourtheye
Array.isArray(arrTerms)
返回
true
因此,如果
results[key]
未定义的
,则
attTerms
会发生什么如果找不到密钥,我们不想做任何事情,是吗?但您仍在调用
arrTerms。forEach
即使
results[key]
未定义。哦,请注意:)ty@ZeMoon:
。.keys
,就像
对象.keys
,将获取对象的所有属性名。因此,如果您有
{foo:undefined}
,那么您将得到
['foo']
。看来,毕竟,您没有发布对象的实际结构:P我想知道为什么没有捕获到它,因为您调用了
console.log(keys)已经存在。