-2

I have a JSON response like this:

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

I want the response to be in the form:

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

How can I achieve this?

user3679294
  • 13
  • 1
  • 7

6 Answers6

1

From the mozilla docs

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
  return a.concat(b);
});
// flattened is [0, 1, 2, 3, 4, 5]
user3995789
  • 3,452
  • 1
  • 19
  • 35
0
var test={"result":[["abc","de"],["fgh"],["ij","kl"]]};
var tmp=[];
for(var i in test.result){
    for(var j in test.result[i]){
      tmp.push(test.result[i][j]);
    }
}
test.result=tmp;
alert(JSON.stringify(test));

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

KyawLay
  • 403
  • 2
  • 10
0

jsFiddle

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

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

var flattenedNative = arrayToFlatten.reduce(function(a, b) {
  return a.concat(b);
});
alert(flattenedNative); // 0,1,2,3,4,5

jQuery (from How to flatten array in jQuery?):

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

Native alternative (from Merge/flatten an array of arrays in JavaScript?):

var flattenedNativeAlt = [].concat.apply([], arrayToFlatten);
alert(flattenedNativeAlt); // 0,1,2,3,4,5
Community
  • 1
  • 1
Benny Bottema
  • 11,111
  • 10
  • 71
  • 96
0

The reduce() and concat() functions can be combined to flatten an array:

var json = {"result":[["abc","de"],["fgh"],["ij","kl"]]};

function concatArrays(a, b) { return a.concat(b); }
json.result = json.result.reduce(concatArrays);

console.log(json);  //{"result":["abc","de","fgh","ij","kl"]}

See it in action:
http://jsfiddle.net/cazomufn/

Dem Pilafian
  • 5,625
  • 6
  • 39
  • 67
0

My first suggestion for this is you should create json directly as you want to use. Do not modify it after you get.

You can also use this , this will give you value as you want.:

    var mainText= JSON.parse('{"result":[["abc","de"],["fgh"],["ij","kl"]]}');
    var arr = [];
    for(var val1 in mainText.result)
    {   
        arr = arr.concat(mainText.result[val1]);
    }   
    mainText.result = arr;
    console.log(JSON.stringify(mainText));
bharatpatel
  • 1,203
  • 11
  • 22
0

I like lodash' flatten (if you can live with another dependency.)

json.result = _.flatten(json.result);  

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

For example reduce isn't supported before IE9 but lodash would still work (compatibility build).

ippi
  • 9,857
  • 2
  • 39
  • 50