Combine two Array objects in one

Deepak Pal1
Kilo Explorer

I have 2 different array in JSON object .

Array1 = [ { "quesText": “Which shift you works in ?" }, { "quesText": " Are you a permanent employee?" }, { "quesText": "Is this your primary or secondary account?” } ]

 

Array2 = [ { "answer": "Evening" }, { "answer": "Morning" }, { "answer": "Yes" }, { "answer": "No" }, { "answer": "Primary" }, { "answer": "Secondary" } ]

 

I want these to combine this way.

How can I achieve this ?

items = [{"Questions" : "Which shift you works in ",

                                    "answer"  : ["Evening","Morning"]},

                                    {"Questions" : "Are you a permanent employee? ",

                                    "answer"  : ["Yes","No"]},

                                    {"Questions" : "Is this your primary or secondary account? ",

                                    "answer"  : ["Primary","Secondary"]}

 

My whole purpose is to use this in NG-REPEAT so it print the question first then answer and then second question.

If any other way to achieve this let me know.

1 ACCEPTED SOLUTION

Deepak Ingale1
Mega Sage

Hi,

here is the code that will give you items what you are looking for

 

Note : Please mark reply as correct if it has answered your question

var Array1 = [{
    "quesText": "Which shift you works in ?"
}, {
    "quesText": " Are you a permanent employee?"
}, {
    "quesText": "Is this your primary or secondary account?"
}];
var Array2 = [{
    "answer": "Evening"
}, {
    "answer": "Morning"
}, {
    "answer": "Yes"
}, {
    "answer": "No"
}, {
    "answer": "Primary"
}, {
    "answer": "Secondary"
}];
var items = [];

for (var i = 0; i < Array1.length; i++) {
    var temp = {};
    temp.Questions = Array1[i]['quesText'];
    temp.answer = [];
    temp.answer.push(Array2[i * 2]['answer']);
    temp.answer.push(Array2[i * 2 + 1]['answer']);
    items.push(temp);
}

View solution in original post

6 REPLIES 6

Chuck Tomasi
Tera Patron

Why wouldn't you use ArrayUtil().union()?

Yes, that would have worked, but I guess he wanted to have a structured array like what he posted in original question, like Questions from 1st Array and then followed by Answered from 2nd Array. 

That is the only reason to write this code 😉