Javascript foreach(多数组)

时间:2018-04-30 08:47:45

标签: javascript arrays

我得到了这个javascript代码,其中我试图访问“recommendedTo”数组但是,当我试图通过foreach访问它时它只是作为[数组]返回而不是数组的确切值。

我做错了什么?

let requestBody = {
    "recommendations":[
        {
            "book" : "12",
            "recommendedTo" : [
                {
                    "employeeId" : "22"
                },
                {
                    "employeeId" : "44"
                }
            ]
        },
        {
            "book": "13",
            "recommendedTo":[
                {
                    "employeeId": "2"
                },
                {
                    "employeeId": "3"
                }
            ]
        }
    ]
};

let messageBody = {
    recommendations: []
};

if (Array.isArray(requestBody.recommendations)) {
    requestBody.recommendations.forEach(function(books, index) {
        messageBody.recommendations.push({
            book: books.book,
            recommended:[]
        }); 
        requestBody.recommendations[index].recommendedTo.forEach(function(book2, index2){
            messageBody.recommendations[index].recommended.push({
                employeeId: book2.employeeId,
            })
        });             
    });
}

console.log(messageBody)

2 个答案:

答案 0 :(得分:0)

更清洁的解决方案

for(let recommendation of requestBody.recommendations){
    for(let recommendedTo of recommendation.recommendedTo){
        console.log(recommendation);
        console.log(recommendedTo);
    }
}

答案 1 :(得分:0)

虽然您的代码有效,但这实际上是地图的一个很好的用例:

 const messageBody = {
    recommendations: requestBody.recommendations.map(({book, recommendedTo}) => ({
        book,
        recommended: recommendedTo.map(({employeeId}) => ({employeeId}))
    }))
 };