如果值存在于所有数组中,则返回true

时间:2018-06-06 19:21:47

标签: javascript node.js

如果Done数组中的所有产品都包含statusLog,我想返回true。如果Done中的任何产品不包含statusLog,则应返回false。某些产品可能没有statusLog属性,这意味着它应该返回false。

代码似乎工作正常,但我觉得必须有更好的方法来重构它。如果没有从第一个产品中找到“完成”,那么它应该跳过循环,因为它不需要保持循环。怎么办?

data={"id":123,"products":[{"id":1,"name":"Item 1","statusLog":[{"name":"New"},{"name":"Done"}]},{"id":2,"name":"Item 2","statusLog":[{"name":"New"},{"name":"Done"}]},{"id":3,"name":"Item 3","statusLog":[{"name":"Pending"},{"name":"Dones"}]},]}

var hasDone = 0;

data.products.forEach((product) => {
  if (product.statusLog) {
     if (product.statusLog.some((status) => {
      return status.name == "Done"
    })) {
         hasDone++
    }
  }
});

if (hasDone != data.products.length) {
    console.log("All products has Done Status")
} 

演示:https://jsfiddle.net/bdrve3xs/18/

2 个答案:

答案 0 :(得分:4)

您可以使用Array.prototype.every

const allHaveDone = data.products.every( 
  product => (product.statusLog || []).some( status => status.name === "Done" )
);

if ( allHaveDone ) {
    console.log("All products has Done Status")
} 

答案 1 :(得分:1)

您可以使用filter并检查其长度。

完成此操作后,您还会获得“未完成”的回复。

Stack snippet

data = {
  "id": 123,
  "products": [{
      "id": 1,
      "name": "Item 1",
      "statusLog": [{ "name": "New" }, { "name": "Done" }]
    },
    {
      "id": 2,
      "name": "Item 2",
      "statusLog": [{ "name": "New" }, { "name": "Done" }]
    },
    {
      "id": 3,
      "name": "Item 3",
      "statusLog": [{ "name": "Pending" }, { "name": "Dones" }]
    },
  ]
}

var not_done = data.products.filter(p => {
  if (!p.statusLog || !p.statusLog.some(s => s.name === "Done")) return p;
});

if (not_done.length > 0) {
  console.log('These/This is not "Done" yet', not_done)
}