开发者

How to compare objects in single array and give validation based on previous object value

I have one array which has n number of objects, suppose if I was having 3 objects, and the value of one property at index 1 is null then the value for the same property is having value in 开发者_如何学编程next index it should show error that previous object value shouldn't be blank

Example sample:[{Id:1, name:'abc'}, {id:2, name:''}, {id:3, name:'dcg'}] Here based on iteration as name is empty at index 1 and having value for name at index 2 it should throw error previous object value name cannot be blank. How to achieve this using forEach


You can simply check items in forEach loop and throw a new exception.

If you wanna prevent that error, you can surround your code block with try catch clause like the following.

const arr = [
  { Id: 1, name: "abc" },
  { id: 2, name: "" },
  { id: 3, name: "dcg" }
];

try {
  arr.forEach(function (x, index) {
    if (index > 0) {
      if (x.name && !arr[index - 1].name) {
        throw "Name is not valid at " + (index - 1);
      }
    }
  });
} catch (e) {

  console.error(e);

  //  Or any error handler here.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜