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.
I am currently utilizing the Date Range Picker plugin for bootstrap from the website http://www.daterangepicker.com/#examples, and I have a requirement to set the maximum date time range to be within 24 hours. Below is an example demonstrating how I can s ...
Recently delving into the world of React, I am utilizing json placeholder along with axios to fetch data. Within my state, I have organized two arrays: one for posts and another for images. state = { posts : [], images : [] ...
In my current application, I am fetching data from an API and everything is functioning correctly. However, I am interested in determining the duration of each request in milliseconds. To achieve this, I implemented interceptors using axios. The challenge ...
Currently, I am utilizing Python in conjunction with Selenium to monitor changes on our pbx system. A specific value that I require is being retrieved through a JavaScript call and unfortunately, it is not directly written into the HTML code. This has made ...
I am attempting to create nested horizontal tabs using MaterialUI. This means having a first level of tabs that, when clicked on, opens a second level of tabs. Here is a link to a working example of the code: https://codesandbox.io/s/sweet-pasteur-x4m8z?f ...
Recently, I've delved into the world of VueJs and I'm encountering some issues with a project that I can't seem to resolve through online resources. I am trying to establish a variable that is common across all pages (month), and whenever t ...
Currently working on my todo list project and I have a question about using innerHTML. I'm curious if I can include an icon inside of a button tag like this: btn.innerHTML = '<i class="fas fa-times fa-lg"></i>'; So, wo ...
I am new to Vue and currently implementing Bootstrap Vue Scrollspy (view example here). My sticky dropdown is tracking all referenced content and updates with the current section in view. You can check out my code sample here. Is there a way to set the d ...
My experience with res.render is flawless: res.render('main', function(err, html){ // Displays '<html></html>' from 'views/main.html' console.log(html); }); However, the situation changes when it comes to ...
I am attempting to change the image of a door from closed to open when the status changes in my home automation dashboard. I need help with this task. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&qu ...
Consider a vanilla JavaScript function like this: if (window.devicePixelRatio >= 2) { document.querySelectorAll('img.retina').forEach(function (e) { let parts = e.src.split('.'); let ext = parts.pop(); i ...
Utilizing the fcm-node package to facilitate sending notifications from the Express API route to the app via a registration token. The function being used is as follows: const FCM = require('fcm-node'); const serverKey = ... const fcm = new FCM( ...
I need to dynamically assign an ng-model variable based on a condition. For instance: <input type="text" ng-model="item.model[multilang]" > The $scope.multilang variable can be set to either "ENG", "JP" (languages) or false. So, when multilang = "E ...
I've been working with React for a while now and I understand how its event system functions. However, I've run into an issue where the onKeyPress event doesn't seem to be triggering on a <canvas> element. Surprisingly, it's not w ...
My task is to remove the "btn" class from items that have an additional argument in their class name, such as: <input type="button" class="btn btn-mini btn-success email-user" id="emailid5" value="Email Tester"> I specifically need to only remove t ...
My webpage contains a div element positioned in the middle of the content, with its height being adjustable through JavaScript code. I am seeking a way to manage the scrolling behavior when the height of the div changes. Specifically, I want the content t ...
How can I modify a local variable within an event handler, listener, or function? export async function mis() { let result; // <--------- LOCAL VARIABLE I WANT TO MODIFY (currently undefined) const m = await spawn(`/cmd`); m.stdout.on('data ...
Currently working on a registration form that involves the use of credit cards. I have reached the stage of form validation to ensure that users input correct data in the appropriate fields. However, this has led me to ponder whether relying on JQuery for ...
I have a PHP function that returns an array with an element error containing the value 'ERR': var updatePaymentType = function(plan_pt_id, pt_id){ var error = null; var data = new Object() data["function"] = "update"; ...
Encountering an error or warning when inputting rows in the table that is causing the screen to freeze. Warning: Maximum update depth exceeded. This issue can arise when a component triggers setState within useEffect, but useEffect doesn't have a de ...