Combine arrays of JSON data within a JSON object using JavaScript

Looking for help with reformatting a JSON response

{"result":[["abc","de"],["fgh"],["ij","kl"]]}

Interested in transforming the response to:

{"result":["abc","de","fgh","ij","kl"]}

What's the best way to accomplish this task?

Answer №1

According to the information found on mozilla docs

We can use the following code snippet to flatten an array in JavaScript:
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
  return a.concat(b);
});
// This will result in 'flattened' being [0, 1, 2, 3, 4, 5]

Answer №2

let data={"values":[["apple","banana"],["orange"],["pear","grape"]]};
let temp=[];
for(let x in data.values){
    for(let y in data.values[x]){
      temp.push(data.values[x][y]);
    }
}
data.values=temp;
alert(JSON.stringify(data));

jsfiddle link http://jsfiddle.net/fu26849m/

Answer №3

Check out this jsFiddle for more

let arrayToFlatten = [[0, 1], [2, 3], [4, 5]];

Using Native JavaScript (source: Merge/flatten an array of arrays in JavaScript?):

let flattenedNative = arrayToFlatten.reduce((a, b) => a.concat(b));
alert(flattenedNative); // Output: 0,1,2,3,4,5

jQuery Method (source: How to flatten array in jQuery?):

let flattenedJQuery = $.map(arrayToFlatten, function(n) { return n; });
alert(flattenedJQuery); // Output: 0,1,2,3,4,5

Alternative Native Approach (source: Merge/flatten an array of arrays in JavaScript?):

let flattenedNativeAlt = [].concat.apply([], arrayToFlatten);
alert(flattenedNativeAlt); // Output: 0,1,2,3,4,5

Answer №4

One solution is to create the desired json directly instead of modifying it later.

Another option is to follow this example:

    var jsonData = JSON.parse('{"result":[["abc","de"],["fgh"],["ij","kl"]]}');
    var array = [];
    for(var value in jsonData.result)
    {   
        array = array.concat(jsonData.result[value]);
    }   
    jsonData.result = array;
    console.log(JSON.stringify(jsonData));

Answer №5

The mergeArrays() function utilizes both the reduce() and concat() methods to flatten an array effectively:

var data = {"output":[["apple","banana"],["cherry"],["dates","figs"]]};

function mergeArrays(x, y) { return x.concat(y); }
data.output = data.output.reduce(mergeArrays);

console.log(data);  //{"output":["apple","banana","cherry","dates","figs"]}

To see it in action:
http://jsfiddle.net/cazomufn/

Answer №6

I really enjoy using Underscore's flatten function (even if it means adding another dependency to my project).

data.info = _.flatten(data.info);

// { info:['apple','banana','cherry','date','elderberry'] }

For instance, map is not compatible with versions of Internet Explorer older than IE9, however, Underscore still performs well across different environments due to its compatibility build.

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

What is the method for storing elements in localStorage within a ReactJs application?

Currently, I am working on learning react-redux and coding a new project. My goal is to implement a feature where clicking the Add Favorites button will push all column data to local storage. Despite reading numerous articles, none of them have provided ...

Clearing existing HTML content in the TR body

I've been struggling with a Jquery/Ajax call that updates cart details. Currently, I can't seem to clear the existing HTML content in the cart-body (tablebody) even though the ajax request adds all the items to the cart successfully. The code sni ...

Guide on integrating angular-schema-form into an Ionic 2.0 project using typescript

Recently, I embarked on creating an app with Ionic from scratch and decided to integrate the framework. While I faced no issues executing the example on a webpage, I encountered difficulties when attempting to do so with Ionic. To kickstart the project, ...

"Extracting information from a database in Angular Laravel to create a Chart.js display - a step-by-step

Currently, I am working on developing a dashboard application that includes various charts. My aim is to customize the data displayed in each user's chart based on information retrieved from a database. This is how my setup looks like: HTML <div ...

Dynamic Population of Django Drop Down List using JavaScript

In my Django + Python website, users can request access to a database through a form that provides them with the following options: Environment: A dropdown list with two values - Development and Production. Permission: Another dropdown list with two val ...

Looking for the MIME file type requirement for Excel or spreadsheets?

Values in the 2nd column indicate the file MIME type. I am looking to create a condition that will be true for all of the above file MIME types. Specifically, I need a condition for all Excel files. This is what I attempted so far: const isXlsFile = !! ...

Ways to create a rounded pane for Highchart's Solidgauge

I've noticed that my arcs have rounded edges, but the pane is flat. Is there a way to make the pane rounded as well? I am currently using Highcharts v9.1.2. I tried using "stroke-linejoin: "round"", but it didn't work. If you need any ...

Maintain the original order of rows in the table while shuffling the columns they appear in randomly

I need help with my table setup. The left column contains words in English, while the right column has the same words translated into Korean. Is there a way to keep the rows intact while randomizing the order of the columns? Here's an example: <ta ...

javascript - Include new parameter in object literal and retrieve

I have a base object that I define using an object literal: var obj = { key1 : 'value1', key2 : 'value2' } Now, I want to pass this object to a function and extend it like this: myFunction( obj + { key3 : 'value3' ...

What's the best way to make a popup link in my situation?

I'm attempting to use Angular to open a popup window in my situation. Here's what I've got: <a ng-href = "window.open('{{videoLink}}')" >open a video</a> When I try this, I get a 'Not found' error in the br ...

Dealing with errors in Express.js within the service or controller layers

Currently, I am developing an Express.js application with a distinct controller layer and service layer. Below you can find the code snippet I have implemented so far: user.service.js exports.registerUser = async function (email, password) { const hash ...

Disable the mousedown event in JavaScript/jQuery

During a drag and drop operation, I have set certain limits on the screen. When the draggable object passes these limits, I want it to return to its original position. The issue I am facing is that if the onmousedown event is active, the object does not r ...

Guide on how to call a function in ascx code-behind using JavaScript within the framework of DotNetN

Currently, I am facing an issue with my module that involves submitting data to a SQL table in a database using code behind. My validation is done through javascript, and when a button is clicked and the data is valid, a div is displayed. However, the pr ...

PHP - A guide to calculate the total value of a multi-level array

I need assistance with finding the total sum of values in this complex array structure: Array ( [1] => 0 [2] => 1 [3] => Array ( [0] => 1 [1] => 1 [2] => 1 ) [4] => 1 [5] => 0 ) The sum in this cas ...

Updating ES6 syntax for superset in array: a step-by-step guide

I am currently working with ES6 React code that generates an array of MiniIcons on a webpage. const MiniIcons = ({miniicons}) => ( <div id="application"> {miniicons.map(miniicon => ( <MiniIcon key={miniicon.id} id={miniicon.id} ...

Enhance autocomplete functionality by adding an additional parameter specific to Zend Framework

My form includes two fields: country club The club field is generated using the ZendX_JQuery_Form_Element_AutoComplete Element, which also creates this javascript code: $("#club").autocomplete({"url":"\/mywebsite\/\/mycontroller\/au ...

Error: Class cannot be loaded by React Webpack loader

I'm encountering an issue with my two typescript packages - a React application and an infrastructure package. The React app has a dependency on the infrastructure package (currently linked via npm). After adding a new class to the infrastructure pack ...

Errored Out: No content found in file_get_contents('php://input') following an ajax post

I've run into a dilemma and am seeking help. I recently encountered an issue where data sent to a PHP file through an AJAX function seemed to vanish when attempting to retrieve it in the PHP file. Strangely enough, a similar function I implemented yes ...

Finding a problem in node.js

I have encountered a problem while creating a server game using node.js. I am seeking assistance to resolve this issue. Here is the specific problem: https://i.stack.imgur.com/FMlsL.png app.js: var express = require('express'); var app = expr ...

Positioning a material UI dialog in the middle of the screen, taking into account variations in its height

Dealing with an MUI Dialog that has a dynamic height can be frustrating, especially when it starts to "jump around" the screen as it adjusts to fit the content filtered by the user. Take a look at this issue: https://i.stack.imgur.com/IndlU.gif An easy f ...