休息;不结束循环

break; not ending for loop

所以我有一些 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'(return false)和'.every'(return true)来突破,但这也没有用。

'post.actions_summary'的正确值应该是{id: 2, count: 10}。

如果我理解得很好,你有一个元素数组,你想要获取第一个元素,它的 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});
}

使用数组filter方法

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

 post.actions_summary = filtered_actions;

答案:

最后,我使用的代码是:

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}];
  }

  });