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?
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?
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]
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/
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
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));
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/
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.
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 ...
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 ...
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, ...
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 ...
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 ...
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 = !! ...
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 ...
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 ...
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' ...
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 ...
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 ...
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 ...
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 ...
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 ...
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} ...
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 ...
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 ...
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 ...
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 ...
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 ...