根据匹配字段组合两个不同的对象数组

8fsztsew  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(233)

我有两个不同的对象数组,需要将这两个数组和预期的最终结果结合起来

[
{
    "scenario": [
        {
            "errorname": "Error 01",
            "status": 5,
            "desc_1" : "test",
            "desc_2" : "testing"
        },
        {
            "errorname": "Error 03",
            "status": 0,
            "desc_1" : "test",
            "desc_2" : "testing"
        },
        {
            "errorname": "Error 09",
            "status": 0,
            "desc_1" : "test",
            "desc_2" : "testing"
        }
    ], 
    "completed": 0,
    "accessid": "1627047023995",
    "oid": 111111
}

]
“a”中的scenario.errorname应与b errorname.name值匹配。我尝试Map并组合这两个数组值,但没有得到期望的值。结果应与errorname匹配,并将两个数组合并以创建一个新数组

let a = [{
  "scenario": [{
      "errorname": "Error 01",
      "status": 5
    },
    {
      "errorname": "Error 03",
      "status": 0
    },
    {
      "errorname": "Error 09",
      "status": 0
    }
  ],
  "completed": 0,
  "accessid": "1627047023995",
  "oid": 111111
}];

let b = [{
    "errorname": [{
        "name": "Error 01",
        "desc_1": "Test",
        "desc_2": "Testing"
      },
      {
        "name": "Error 03",
        "desc_1": "Test",
        "desc_2": "Testing"
      },
    ],
  },
  {
    "errorname": [{
        "name": "Error 02",
        "desc_1": "Test",
        "desc_2": "Testing"
      },
      {
        "name": "Error 09",
        "desc_1": "Test",
        "desc_2": "Testing"
      },
    ]
  }
]

const c = a.map(t1 => ({ ...t1,
  ...b.find(t2 => t2.errorname.name === t1.scenario.errorname)
}))
console.log(c)
jfewjypa

jfewjypa1#

下面是一个先做一个 Map 从数组 bname 然后用这个来访问相关的 error 中的对象 map() 调用数组 a .

const a = [{ "scenario": [{ "errorname": "Error 01", "status": 5 }, { "errorname": "Error 03", "status": 0 }, { "errorname": "Error 09", "status": 0 }], "completed": 0, "accessid": "1627047023995", "oid": 111111 }];
const b = [{ "errorname": [{ "name": "Error 01", "desc_1": "Test: 01", "desc_2": "Testing" }, { "name": "Error 03", "desc_1": "Test: 03", "desc_2": "Testing" },], }, { "errorname": [{ "name": "Error 02", "desc_1": "Test: 02", "desc_2": "Testing" }, { "name": "Error 09", "desc_1": "Test: 09", "desc_2": "Testing" },] }];

// Map { 'Error 01' => { desc_1: 'Test', desc_2: 'Testing' }, 'Error 03' => {...}, ...}
const errorMap = new Map(b
  .flatMap(o => o.errorname)
  .map(({ name, ...e }) => [name, e]));

const result = a.map(t1 => (
  {
    ...t1,
    scenario: t1.scenario.map(s => ({ ...s, ...errorMap.get(s.errorname) }))
  }));

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

相关问题