Fonty
Fonty

Reputation: 159

How to ignore the loop in else case

I have to compare two values. Both values came from different loops. if the value is an exact match, I push the array differently.

As you can see in the code. I cant use an "else" after the "if" function because it will literate till the loop stop. I would have multiple pushes.

If I add the array.push after the loop there will be 2 pushes.


for (var prop in obj) {
    var array = []
    for (var item in obj[prop]) {
        for (var i = 0; i < doctyp88.length; i += 1) {

            var doctyp88ID = doctyp88[i]._id;
            var doctyp88name = doctyp88[i]._source['88_name'];

            if (item == doctyp88ID) {
                array.push({
                    "name": item,
                    "count": obj[prop][item],
                    "archivname": doctyp88name,
                });
            }
        }

        array.push({
            "name": item,
            "count": obj[prop][item],

        });
    }
}

What is the best way to avoid my problem?

Upvotes: 0

Views: 191

Answers (2)

IP_
IP_

Reputation: 695

for (var prop in obj) {
    var array = []
    for (var item in obj[prop]) {
        const newObj = {
               "name": item,
         } 
        for (var i = 0; i < doctyp88.length; i += 1) {

            var doctyp88ID = doctyp88[i]._id;
            var doctyp88name = doctyp88[i]._source['88_name'];

            newObj.count= obj[prop][item],


            if (item == doctyp88ID) {
                newObj.archivname = doctyp88name
            }
        }

        array.push(newObj);
    }
}

Upvotes: 1

Minwork
Minwork

Reputation: 1022

If I understood your question correctly you could use break [label]; statement to exit from nested loop and skip more pushes but don't exit outside for like this:

loop_1:
for (var prop in obj) {
    var array = []

    loop_2:
    for (var item in obj[prop]) {

        loop_3:
        for (var i = 0; i < doctyp88.length; i += 1) {

            var doctyp88ID = doctyp88[i]._id;
            var doctyp88name = doctyp88[i]._source['88_name'];

            if (item == doctyp88ID) {
                array.push({
                    "name": item,
                    "count": obj[prop][item],
                    "archivname": doctyp88name,
                });
                break loop_2;
            }
        }

        array.push({
            "name": item,
            "count": obj[prop][item],

        });
    }
}

Upvotes: 0

Related Questions