You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对比两个JSON数组,将匹配项的grade字段合并至目标数组?

Hey there! Let's figure out how to merge those two arrays exactly like you need. The goal is to take each item in array a, find its matching entry in array b using the id/student_id match, and then attach the grade to the corresponding item in a. Here are two practical, easy-to-implement ways to do this in JavaScript:

Approach 1: Simple map() + find() (Great for Smaller Datasets)

This method is super readable and straightforward—perfect if you don't have a massive amount of data to process:

// Your original arrays
const a = [{"id":"1","mark":"96"},{"id":"2","mark":"65"}];
const b = [{"student_id":"1","grade":"A"},{"student_id":"2","grade":"c"}];

// Merge the grade into array a
const c = a.map(itemFromA => {
  // Find the matching item in b where student_id matches a's id
  const matchFromB = b.find(itemFromB => itemFromB.student_id === itemFromA.id);
  
  // If we found a match, combine the original item with the grade; otherwise keep the original
  return matchFromB ? {...itemFromA, grade: matchFromB.grade} : itemFromA;
});

console.log(c);
// Output: [{"id":"1","mark":"96","grade":"A"}, {"id":"2","mark":"65","grade":"c"}]

Approach 2: Lookup Object (More Efficient for Large Datasets)

If you're working with a lot of entries, this method is way faster. Instead of searching through array b every time (which gets slow for big data), we first turn b into a lookup object for instant access:

const a = [{"id":"1","mark":"96"},{"id":"2","mark":"65"}];
const b = [{"student_id":"1","grade":"A"},{"student_id":"2","grade":"c"}];

// Convert array b into a lookup object: { "1": "A", "2": "c" }
const gradeLookup = b.reduce((lookup, item) => {
  lookup[item.student_id] = item.grade;
  return lookup;
}, {});

// Now map over array a and pull the grade from the lookup
const c = a.map(item => ({
  ...item,
  grade: gradeLookup[item.id] // Will be undefined if no match—adjust if needed (e.g., || '')
}));

console.log(c);
// Same desired output as above!

Quick Heads-Up:

If there are multiple entries in b with the same student_id, the first approach will grab the first matching entry, while the lookup object approach will grab the last one. Just keep that in mind depending on your specific data structure!

内容的提问来源于stack exchange,提问作者midhun k

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:48:58