2016-02-28 215 views
0

所以我有一些JSON數據,我試圖解析。 'id:2'是'like-count'的等效動作ID。出於測試目的,我設置的「post.actions_summary」到陣列,休息;不結束循環

post.actions_summary.push({id: 5, count: 2}, {id: 6, count: 2}, {id: 2, count: 10}, {id: 10, count: 10}); 

的代碼應該通過此陣列來解析低於:

for (i = 0; i < post.actions_summary.length; i++) { 
    action = post.actions_summary[i]; 

    if (action.id === 2) { 
    aID = action.id; 
    aCOUNT = action.count; 
    post.actions_summary = []; 
    post.actions_summary.push({id: aID, count: aCOUNT}); 
    break; 
    } else { 
    post.actions_summary = []; 
    post.actions_summary.push({id: 2, count: -1}); 
    } 
} 

然而,檢查的值時'post.actions_summary',我不斷收到一個數組,其中包含'id:2,count:-1'。我也嘗試過使用'.some'(返回false)和'.every'(返回true),但這也不起作用。

'post.actions_summary'的正確值應該是{id:2,count:10}。

+0

使用'console.log(JSON.stringify(a );'看看每個迭代在做什麼 –

+0

當我把你的代碼放在'action ='的下面,if循環之前,web控制檯返回的是: {「id」:5, 「count」:2} | 1 | post.actions_summary | [Object count:1id:2__proto__:Object] –

+0

我實際上認爲我可能知道......在第一個ELSE語句之後,'.length'基本上爲0,這樣循環在第一次迭代時終止。我應該嘗試爲.length設置一個變量來保存實際值。現在測試。 現在我得到一個錯誤(Uncaught TypeError:無法讀取未定義(...)的屬性'id'),當把'我<長度' –

回答

0

使用陣列filter方法

filtered_actions = post.actions_summary.filter(function(action){ 
     return action.id == 2 
    }); 

post.actions_summary = filtered_actions; 
+0

添加中,如果(typeof運算filtered_actions [0] == 「未定義」){ post.actions_summary.push({ID:2,計數:0}) } 來提供默認值如果沒有找到。謝謝! –

0

如果我理解的很好,你有一個元素數組,並且你想得到第一個元素的id等於「2」,如果沒有元素的id等於「2」你想要使用默認元素(值等於「-1」)初始化您的數組。

如果我是對的,算法中會有一個錯誤:如果數組中的第一個元素不等於「2」,則使用默認元素初始化數組,而不管數組的大小如何總是會停在第一個元素上。

一種可能的解決方案:

var post = {actions_summary:[]}; 
post.actions_summary.push({id: 5, count: 2}, {id: 6, count: 2}, {id: 2, count: 10}, {id: 10, count: 10}); 
var result = []; // bad idea to edit the size of post.actions_summary array during the loop 
var found = false 

for (var i = 0; i < post.actions_summary.length && !found; i++) { 
    action = post.actions_summary[i]; 
    found = action.id === 2; 

    if (found) { 
    aID = action.id; 
    aCOUNT = action.count; 
    result.push({id: aID, count: aCOUNT}); 
    } 
} 

if(!found){ 
    result.push({id: 2, count: -1}); 
} 
+0

這個作品呢!感謝您的意見:) –

0

解答:

最後,我使用的代碼是:

posts.forEach(function(post) { 

    filtered_actions = 

    post.actions_summary.filter(function(action){ 
     return action.id == 2 
    }); 

    if (typeof filtered_actions[0] !== "undefined") { 
    post.actions_summary = filtered_actions; 
    } else { 
    post.actions_summary = [{id: 2, count: 0}]; 
    } 

    });