Merge adjacent elements within an array to create a fresh array

Here is a demo array with a variable length (n).

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

I am looking to combine two consecutive objects for the desired output.

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

Any ideas on how I can achieve this using JavaScript? I've been stuck on it for the past couple of days.

Answer №1

If you're looking for a similar solution, you can give this code a try:

const info = [{
"name": "topic",
"value": "this is the first topic"
},
{
"name": "description",
"value": "this is the first description"
},
{
"name": "topic",
"value": "this is the second topic"
},
{
"name": "description",
"value": "this is the second description"
}
];

let newInfo = [];
for(let index=0,length=info.length;index<length;index=index+2) {
newInfo.push({
topic:info[index].value,
description: (info[index+1]||{}).value
});
}

console.log(newInfo);

Answer №2

Transform the array into two-element sub-arrays using the combination of map() and filter() methods, then convert these sub-arrays into objects utilizing the reduce method.

const questionsAndAnswers = [{
        "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 transformedArray = questionsAndAnswers
//using map to create two-element sub-arrays; only odd values are mapped while even ones are []
.map((qa,i,arr) => i % 2 === 0 ? [qa,arr[i+1]] : [])
//only keeping sub-arrays with content (not empty)
.filter(qa => qa.length)
//converting each sub-array into an object
.map( qa => qa.reduce((transformedObj,{name,value}) => ({...transformedObj,[name]:value}), {}) );

console.log( transformedArray );

Employing reduce() in place of map() and filter()

const questionsAndAnswers = [{
        "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 transformedArray = questionsAndAnswers
//convert the original array into two-element sub-arrays
.reduce((acc,qa,i,arr) => i % 2 === 0 ? [...acc,[qa,arr[i+1]]] : acc, [])
//convert each sub-array into an object
.map( qa => qa.reduce((transformedObj,{name,value}) => ({...transformedObj,[name]:value}), {}) );

console.log( transformedArray );

Using solely reduce()

const questionsAndAnswers = [{
        "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 transformedArray = questionsAndAnswers
.reduce(
    (acc,{name,value},i,arr) => 
    i % 2 === 0 ? [...acc,{[name]:value,[arr[i+1].name]:arr[i+1].value}] : acc, []
);

console.log( transformedArray );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Objects within an array are not sorted based on their properties

I'm currently struggling with sorting an array of objects based on a specific property. Despite my efforts, I can't seem to figure out what's causing the issue as it remains unsorted. Would appreciate some assistance. You can take a look at ...

JavaScript accordions failing to open

I've encountered an issue with my website that includes JS accordions. Strangely, they are not opening on the live site, but they function properly on Codepen. I checked the console in Chrome and found no error messages, however, when I looked at the ...

What is the best way to integrate a VueJS application into an already established web page?

Working on a project involves fixing issues with legacy components in a server-rendered web page. I proposed rewriting these parts in Vue to facilitate our migration, and the team approved. I created a mini-app using the Webpack template from Vue CLI, whi ...

The debounce functionality provided by Lodash does not seem to be functioning properly within VueJS events

I am attempting to incorporate the debounce function into my filter. The goal is to avoid sending a request with each change in input text, and instead, wait for about one second. However, I'm encountering an issue where the filter doesn't seem ...

Tips for making sure your published npm package respects the baseUrl specified in the tsconfig.json file

I am currently developing an npm library using TypeScript. Within our project configuration, we have specified a baseUrl in our tsconfig.json file. "baseUrl": "src", When referencing files within the src directory, we can simply use: src |-folderA ...

The jQuery .load() method fails to retrieve a valid value from @Url.Action

Being new to MVC, I need a simple and specific explanation. I am trying to open a modal dialog using jQuery but @Url.Action is returning a null value. If I hardcode the path instead, it works fine. Here's the code snippet below. Script: <script t ...

Creating a platform for users to share their thoughts and engage in

A friend and I are working on creating a commenting system for our website. We have written some code to insert values into a mysql database so that they can be read and displayed as comments later on. Unfortunately, we are facing an issue where the data i ...

Creating a Vue application without the use of vue-cli and instead running it on an express

Vue has an interesting feature where vue-cli is not necessary for running it without a server. Initially, I thought otherwise. The Vue installation page at https://v2.vuejs.org/v2/guide/installation.html mentions using a script under CDN. <script src=&q ...

Looking to adjust the title font size when exporting DataTable to Excel?

Would like to customize the title of an excel file exported from Datatable. I attempted to implement a solution found on a stackoverflow post, but it ended up applying the customization to the entire sheet. $("#datatable").DataTable({ ...

What is preventing me from displaying my paragraph?

I have some content that I want to show a paragraph with the class paragraphtoggle when clicked, but it's not working as expected. Here is what I have tried: https://example.com/jsfiddle HTML <div class="enzimskiprogramindex herbaprogramindex he ...

Tips for displaying two input decorations in Material UI beside one another within a text field

In the Text Field demonstration, I noticed input adornments at the start and end. However, I am looking to have two input adornments at the end specifically. I attempted to add them using endAdornment: {InputAdornment InputAdornment}, but encountered an er ...

What is the best way to send an array to a modal?

Utilizing Axios for retrieving a list of countries from a REST API, I have implemented modals with each displaying the name and flag of a country. Upon clicking on any country name, the console will log the selected country. I am looking to pass the last ...

In version 81 of Three.js, the toShapes() function has been relocated to a new class. Find out how

After updating Three.js from v73 to v81, I encountered the following error: Uncaught TypeError: path.toShapes is not a function Upon reviewing the new release notes, I discovered the following changes made to Path: The removal of .actions (yay) Movin ...

What is the best way to display the contents of an array across multiple lines?

Whenever I try to print out the array in the terminal, it always appears on a single line. Is there a way to display each array on its own separate line instead? array = [[1, 2, 3], [8, 9, 4], [7, 6, 5]] ...

Customizing buttons on Dialogs in JavaScript to have dynamic names

There is something on my website that resembles this: $("#id").html(msg2show).dialog({ //Other attributes buttons: { "Yes": function() {//Code}, "No": function() {//Code} } ...

Why isn't PHP json_encode properly encoding data?

Here is an example of the array structure stored in $arrayResult: array (size=1) 'Records' => array (size=1498) 0 => array (size=4) 'code' => string '9999999' (length=12) &ap ...

Validating forms with dynamically populated fields using Jquery

Having trouble with Jquery Validation on dynamically populated fields. In my asp.net project, I need the name fields to remain constant because I split an array of information on the server side and update a database. <form id="insert_additions" action ...

Transform the components of an array into a mathematical formula and store it in a variable

I am working with an array that contains boolean values (True, False) and strings representing logical operators (‘and’, ‘or’, ‘not’). For example: array = [True, 'and', False] I want to convert these elements into an actual express ...

Using PHP to convert JSON into a multi-dimensional array

I am working with a json file that contains numerous records with fields such as date, time, and isApproved. My goal is to extract all the approved records, organize them by date, and list all the booked hours for each date. For example: [{"fullName":" ...

Dealing with Angular.js $http intercept error "net::ERR_CONNECTION_REFUSED"

Currently, I am attempting to create a universal error handler for my website utilizing $http interceptors. However, it seems that the interceptors are not functioning as intended. I have set up interceptors for 'response' and 'responseErro ...