如何在JavaScript中合并JSON格式的多组stores对象数组?
合并嵌套的Stores数组为平级数组
问题描述
输入JSON结构:
[ { "stores": [ { "name": "My store", "location": "NY" }, { "name": "Other store", "location": "FL" }, { "name": "My other store", "location": "NY" } ] }, { "stores": [ { "name": "Another My store", "location": "NY" }, { "name": "Some Other store", "location": "FL" }, { "name": "Secondary store", "location": "NY" } ] } ]
期望输出:
[ { "name": "My store", "location": "NY" }, { "name": "Other store", "location": "FL" }, { "name": "My other store", "location": "NY" }, { "name": "Another My store", "location": "NY" }, { "name": "Some Other store", "location": "FL" }, { "name": "Secondary store", "location": "NY" } ]
你当前代码里的Object.keys(item.stores)是错误用法——item.stores本身就是数组,Object.keys会返回数组的索引(比如["0","1","2"]),这不是你需要的内容。下面是几种可行的解决方案:
解决方案1:forEach + 展开运算符
遍历输入数组,把每个stores数组的元素展开后推入结果数组:
const input = [/* 你的输入数据 */]; let grouped = []; input.forEach(item => { // 用展开运算符把item.stores的每个元素单独push进grouped grouped.push(...item.stores); }); console.log(grouped);
解决方案2:flatMap(最简洁)
flatMap会先映射每个元素,再自动扁平化一层数组,刚好匹配需求:
const input = [/* 你的输入数据 */]; const grouped = input.flatMap(item => item.stores); console.log(grouped);
解决方案3:reduce + concat
用reduce累加数组,每次把当前项的stores拼接到累加器里:
const input = [/* 你的输入数据 */]; const grouped = input.reduce((acc, curr) => acc.concat(curr.stores), []); console.log(grouped);
这三种方法都能得到你想要的平级数组,其中flatMap是ES2019引入的方法,现代浏览器和Node.js都支持;如果需要兼容旧环境,reduce或forEach的方案更稳妥。
内容的提问来源于stack exchange,提问作者Rain Man
相关产品推荐
相关产品推荐

