0

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?

2 Answers 2

1
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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is brilliant. Thanks alot
0

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],

        });
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.