【问题标题】:How to merge multiple json arrays into one array swift sub array in Javascript?如何在Javascript中将多个json数组合并为一个数组swift子数组?
【发布时间】:2019-03-01 11:11:19
【问题描述】:

我有两个 json 数组:

     1) 
    [
      {
       "userId": 9
      },
      {
       "userId": 14
      }
     ]

     2) 
     [{"role": "1", "group": "3"}, {"role": "1", "group": "2"}] 

我想合并两个数组,如下所示: 是否有可能通过javascript获得解决方案?

    [
     {"userId":9,"role":"1","group":"2"},
     {"userId":14,"role":"1","group":"2"}
     {"userId":9,"role":"1","group":"3"},
     {"userId":14,"role":"1","group":"3"}
    ] 

我尝试使用 Let 但是我找不到操作切换子数组的方法:

     let arr1 = 
     [{ "userId": 9 }, { "userId": 14 }]
     let arr2 = [{"role": "1","group": "3"}, {"role": "1","group": "2" }] 

     let result = arr1.map(o => Object.assign(o, ...arr2));

     console.log(result);
    return result;

结果是这样的:

    [{"userId":9,"role":"1","group":"2"},{"userId":14,"role":"1","group":"2"}] 

提前致谢。

【问题讨论】:

  • StackOverflow 不是编码服务。请问你试过什么?出了什么问题?
  • 你在正确的轨道上。但是您需要map 处理x 的元素,而不是简单地将它们应用于它。有关更简单的方法,请参阅 Mohammad Usman 的答案。

标签: javascript arrays json merge


【解决方案1】:

@Mohammad Usman 有一个更好的答案,但更容易理解的一个方法是创建一个具有所需值的新对象并将其推送到结果数组中。如下:

users = [
    {"userId": 9},
    {"userId": 14}
];

data = [
    {"rid": 1},
    {"mid": 201}
];
result = [];

for (var i = 0; i < users.length; i++) {
    result.push({
        "rid": data[0].rid,
        "mid": data[1].mid,
        "userId": users[i].userId
    });
}

这里result 将有所需的输出。

【讨论】:

    【解决方案2】:

    您可以将.map()Object.assign() 一起使用:

    let arr1 = [{"userId": 9}, {"userId": 14}],
        arr2 = [{"rid": 1}, {"mid": 201}];
         
    let result = arr1.map(o => Object.assign(o, ...arr2));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

    • 我用数组编辑问题。你能看看它是如何工作的吗?
    猜你喜欢
    • 2019-03-04
    • 2012-05-10
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 2013-12-25
    相关资源
    最近更新 更多