简体   繁体   English

打破每个循环 javascript

[英]Breaking out of for each loop javascript

So I have an object here called computedJobs,所以我有一个 object 这里叫做 computedJobs,

{
  'a': [{'_id': '1'}, {'_id': '2'}, {'_id': '3'} ],
  'b': [{'_id': '4'}]
}

What I'm trying to do is, trying to delete an object with the '_id' as '1'.我想要做的是,尝试删除一个'_id'为'1'的object。

So what my initial thought was, to loop through it and then when I find the item I break out and delete that item.所以我最初的想法是,循环遍历它,然后当我找到该项目时,我打破并删除该项目。 This is what I have written,这是我写的,

var res;
          for (var key in this.computedJobs) {
            for(var i=0; i<this.computedJobs[key].length; i++) {
              console.log(this.computedJobs[key])
              if (this.computedJobs[key][i]._id === '1') {
                res = this.computedJobs[key][i]
                break
              }
            }
          }

But the res comes as undefined.但是res是未定义的。

On the other hand, I had tried,另一方面,我试过,

var res;
          for (var key in this.computedJobs) {
            this.computedJobs[key].forEach(j => {
              if (j._id === '1') {
                res = j
                break
              }
            })
          }

But I get an error Syntax Error: Unsyntactic break .但我收到一个错误Syntax Error: Unsyntactic break Can anyone please tell me what I'm doing wrong?谁能告诉我我做错了什么?

Just find the index of the object and splice the array.只需找到 object 的索引并拼接数组即可。

var index = this.computedJobs[key].findIndex(j => j._id === '1');
if ( index >= 0 ) {
  this.computeJobs.splice(index, 1);
}

If you know for a fact that you have at most 1 matching "object", you can use Array#some and splice the object out of the array如果您知道您最多有 1 个匹配的“对象”,您可以使用Array#some并将 object 从数组中splice出来

 var data = { 'a': [{'_id': '1'}, {'_id': '2'}, {'_id': '3'} ], 'b': [{'_id': '4'}] }; Object.values(data).some(v => v.some(({_id}, index, array) => { console.log(_id); if (_id === '1') { return array.splice(index, 1); return true; } })); console.log(data);

By using Array#some, the iteration stops as soon as a truthy value is returned from the callback - so you can see, the only tested object is the one you want to remove - quick and efficient, no unnecessary iterations通过使用 Array#some,一旦回调返回真值,迭代就会停止 - 所以你可以看到,唯一经过测试的 object 是你想要删除的 - 快速高效,没有不必要的迭代

Let's see what happens if we delete id 5让我们看看如果我们删除 id 5 会发生什么

 var data = { 'a': [{'_id': '1'}, {'_id': '2'}, {'_id': '3'} ], 'b': [{'_id': '4'}, {'_id': '5'}, {'_id': '6'}] }; Object.values(data).some(v => v.some(({_id}, index, array) => { console.log(_id); if (_id === '5') { return array.splice(index, 1); return true; } })); console.log(data);

You can see it你可以看到

The code below probably isn't what you need - but included just in case下面的代码可能不是您需要的 - 但以防万一

If there can be multiple objects with same ID, then it's a little more complex如果可以有多个具有相同 ID 的对象,那么它会更复杂一些

I use reduceRight as a convenient way of functionally iterating through an array from end to start, as that's how you want to do it if you're mutating the array我使用reduceRight作为从头到尾对数组进行功能迭代的便捷方式,因为如果你正在改变数组,这就是你想要的方式

 var data = { 'a': [{'_id': '1'}, {'_id': '2'}, {'_id': '3'} ], 'b': [{'_id': '4'}] }; Object.values(data).forEach(v => v.reduceRight((_, {_id}, index, array) => { if (_id === '1') { array.splice(index, 1); } }, null)); console.log(data);

I tried your code and made minimal changes required:我尝试了您的代码并进行了最少的更改:

let objToDelete =   {
                    'a': [{'_id': '1'}, {'_id': '2'}, {'_id': '3'} ],
                    'b': [{'_id': '4'}]
                  };
var res =   {};                 
for (var key in objToDelete) {
   for(var i=0; i<objToDelete[key].length; i++) {
     if (objToDelete[key][i]._id === '1') {
       res = objToDelete[key][i];
       break;
     }
   }
}

if(Object.keys(res).length && res.hasOwnProperty('_id')){
    console.log('Yes we got the element!');
}
else{
    console.log('Object not found!');
}

console.log(res)

And it's working.它正在工作。

Please try this:请试试这个:

const jsonObj = {
  'a': [{'_id': '1'}, {'_id': '2'}, {'_id': '3'} ],
  'b': [{'_id': '4'}]
};

let result;
const keys = Object.keys(jsonObj);

keys.forEach(k => {
  const obj = jsonObj[k].find(o => o._id === '1');
  if (obj) return result = obj;
});
console.log('Result: ', result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM