将json对象的不同字段的值组合成单个数组

时间:2017-10-10 05:50:11

标签: javascript jquery json ajax

在对某个url进行ajax调用之后,我以格式的json对象的形式返回数据:

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

我想结合feild1和feild2的值,以便我有一个类型的数组:

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

因此我可以将此单个数组发送到响应函数以进行自动完成。如果我发送data.feild1然后data.feild2,则data.feild2的值只会显示在下拉列表中。

4 个答案:

答案 0 :(得分:1)

使用Object#keys迭代Array#map以将数组提取到数组数组,然后应用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);




或者使用ES6 spread syntaxObject#Values来提取子数组:



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

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

console.log(result);




答案 1 :(得分:0)

从响应中设置两个数组:

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

假设您在密钥response中获得响应,然后

var array1 = response.field1;

var array2 = response.field1;

然后使用concat函数

连接两个数组

答案 2 :(得分:0)

使用数组连接创建单个数组

let responseArray = [];

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

回复responseArray

答案 3 :(得分:0)

只需在EcmaScript6中使用传播参数

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

var result = [...array1.feild1, ...array1.feild2 ];