0

After making an ajax call to a certain url I am returned data in the form of a json object of the format:

{"feild1":["val1","val2","val3",...,"valn"],
 "feild2":["vala","valb","valc",...,"valx"]}

I want to combine the values of feild1 and feild2 so that I have a single array of the type :

["val1","val2","val3",...,"valn","vala","valb","valc",...,"valx"]

So I can send this single array to the response function for autocomplete. If I send data.feild1 and then data.feild2 then values of data.feild2 only show up in the drop down.

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Use array concat – John R Oct 10 '17 at 05:52
  • Possible duplicate of [How to merge two arrays in Javascript and de-duplicate items](https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items) – Xpleria Oct 10 '17 at 06:21

4 Answers4

1

Iterate the Object#keys with Array#map to extract the arrays to an array of arrays, and then flatten by applying Array#concat:

var data = {"feild1":["val1","val2","val3","valn"], "feild2":["vala","valb","valc","valx"]};

var result = [].concat.apply([], Object.keys(data).map(function(key) {
  return data[key];
}));

console.log(result);

Or by using ES6 spread syntax and Object#Values to extract the sub arrays:

const data = {"feild1":["val1","val2","val3","valn"], "feild2":["vala","valb","valc","valx"]};

const result = [].concat(...Object.values(data));

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

set both arrays from your response :

var array1 = ["val1","val2","val3",...,"valn"];
var array2 = ["vala","valb","valc",...,"valx"];
var new_merged_array = array1.concat(array2);
console.log(new_merged_array)

Suppose you get the response in key response, then

var array1 = response.field1;

var array2 = response.field1;

Then concat both of the array using concat function

Sagar Jajoriya
  • 2,377
  • 1
  • 9
  • 17
0

Using array concat to create a single array

let responseArray = [];

for (var key in data) {
  if (data.hasOwnProperty(key)) {
    responseArray.concat(data[key]);
  }
}

Respond with responseArray

nilobarp
  • 3,806
  • 2
  • 29
  • 37
0

Just use spread parameters in EcmaScript6

var array1 = {
  "feild1":["val1","val2","val3","valn"],              
  "feild2":["vala","valb","valc","valx"]
};

var result = [...array1.feild1, ...array1.feild2 ];
Ehsan Arian
  • 121
  • 7