2016-02-28 166 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}]; 
    } 

    });