Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combine consecutive objects in an array to form a new array

This is my sample array. Array length can be n

[{
"name": "question",
"value": "this is a first question"
},
{
"name": "answer",
"value": "this is a frist answer"
},
{
"name": "question",
"value": "this is a second question"
},
{
"name": "answer",
"value": "this is a second answer"
}
]

I want the following output by combining two consecutive objects.

[{"question":"This is first question", "answer":"This is first answer"}, {"question":"This is second question", "answer":"This is second answer"}]

What should be my javascript to achieve the same? I am stuck here for the last 2 days

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Convert the array into one with two-element sub-arrays using map() and filter() methods, then convert the sub-arrays into objects using reduce method.

const exam = [{
        "name": "question",
        "value": "this is a first question"
    },
    {
        "name": "answer",
        "value": "this is a frist answer"
    },
    {
        "name": "question",
        "value": "this is a second question"
    },
    {
        "name": "answer",
        "value": "this is a second answer"
    }
];

const newExam = exam
//map each odd element to a two-element sub-array; even []
.map((q,i,a) => i % 2 === 0 ? [q,a[i+1]] : [])
//filter out []
.filter(q => q.length)
//convert each sub-array into an object
.map( q => q.reduce((qn,{name,value}) => ({...qn,[name]:value}), {}) );

console.log( newExam );

Using reduce() instead of map() and filter()

const exam = [{
        "name": "question",
        "value": "this is a first question"
    },
    {
        "name": "answer",
        "value": "this is a frist answer"
    },
    {
        "name": "question",
        "value": "this is a second question"
    },
    {
        "name": "answer",
        "value": "this is a second answer"
    }
];

const newExam = exam
//convert array into two-element sub-arrays
.reduce((ex,q,i,a) => i % 2 === 0 ? [...ex,[q,a[i+1]]] : ex, [])
//convert each sub-array into an object
.map( q => q.reduce((qn,{name,value}) => ({...qn,[name]:value}), {}) );

console.log( newExam );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading