gpt4 book ai didi

javascript - 将 json 对象的不同字段的值合并到单个数组中

转载 作者:行者123 更新时间:2023-12-03 03:18:49 25 4
gpt4 key购买 nike

对某个 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 的值仅显示在下拉列表中。

最佳答案

迭代Object#keysArray#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);

关于javascript - 将 json 对象的不同字段的值合并到单个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46659426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com