js 如何根据两个数组中某个字段关联拼接数据?

新手上路,请多包涵

以 model 值关联拼接数据

var aa = [{"sales": "33", "brand": "4", "model": "ITsdwd", "quotetime": "2022/11/10 1:43:15 上午"}]
var bb = [ {
"supplier": "aaa",
"brand": "10",
"model": "AAA11",
"itemencap": "",
"costps": "",
"purchaser": "152",
"stocksl": ""
}, {
"supplier": "测试供应商",
"brand": "4",
"model": "ITsdwd",
"itemencap": "",
"costps": "",
"purchaser": "33",
"stocksl": "1000"
}]

得到以下内容

[
    {
        "supplier": "aaa",
        "brand": "10",
        "model": "AAA11",
        "itemencap": "",
        "costps": "",
        "purchaser": "152",
        "stocksl": ""
    },
    {
        "supplier": "测试供应商",
        "brand": "4",
        "model": "ITsdwd",
        "itemencap": "",
        "costps": "",
        "purchaser": "33",
        "stocksl": "1000",
        "sales": "33",
        "quotetime": "2022/11/10 1:43:15 上午"
    }
]
阅读 1.6k
3 个回答

这样?

bb.map(i => Object.assign(i, aa.find(j => i.model === j.model)))
新手上路,请多包涵

已找到解决方法

for (var i = 0; i < bb.length; i++) {
    var model_B = bb[i].model;
    for (var j = 0 ; j < aa.length; j++) {
        var model_A = aa[j].model;
        if (model_B == model_A) {
            bb[i].sales = aa[j].sales;
            bb[i].brand = aa[j].brand;
            bb[i].model = aa[j].model;
            bb[i].quotetime = aa[j].quotetime;
        }
    }
}

console.log("bb", bb);

map 一下,然后合并一下。当然,你也可以只取 quotetime 字段

bb.map(b=>{
    const a = aa.find(a=>a.model == b.model);
    return {...a,...b}
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题