我有2个名为
的数组a = [{"id":"1","mark":"96",...},{"id":"2","mark":"65",...}];
b = [{"student_id":"1","grade":"A"},{"student_id":"2","grade":"c"}];
我想比较2个数组,如果'id'和'student_id' 匹配,我想将等级值推送到' '阵列。然后我的结果将是:
预期结果:
c = [{"id":"1","mark":"96","grade":"A",...},
{"id":"2","mark":"65","grade":"c".....}];
答案 0 :(得分:4)
以下是n
复杂性:
const a = [{
"id": "1",
"mark": "96"
}, {
"id": "2",
"mark": "65"
}];
const b = [{
"student_id": "1",
"grade": "A"
}, {
"student_id": "2",
"grade": "c"
}];
let map = a.reduce((acc, item) => {
acc[item.id] = item;
return acc;
}, {});
b.forEach(item => {
if (map[item.student_id]) {
map[item.student_id].grades = item.grade;
}
});
console.log(Object.values(map));

答案 1 :(得分:2)
使用.find
标识另一个数组中的匹配元素,并使用.reduce
从中创建一个新对象:
const marks = [{"id":"1","mark":"96"},{"id":"2","mark":"65"}];
const students = [{"student_id":"1","grade":"A"},{"student_id":"2","grade":"c"}];
const result = marks.reduce((resultsSoFar, mark) => {
const id = mark.id;
const grade = students.find(({ student_id }) => student_id === id).grade;
resultsSoFar.push({ ...mark, grade });
return resultsSoFar;
}, []);
console.log(result);
答案 2 :(得分:2)
您可以使用数组' map()
和forEach()
来执行以下操作:
var a = [{"id":"1","mark":"96"},{"id":"2","mark":"65"}];
var b = [{"student_id":"1","grade":"A"},{"student_id":"2","grade":"c"}];
var c = a.map(function(i){
b.forEach(function(j){
if(i.id===j.student_id){
i.grade = j.grade;
}
});
return i;
})
console.log(c);

答案 3 :(得分:0)
您可以使用for
循环来遍历数组a
和数组b
,然后只要您在id
和student_id
值匹配时添加grade
属性并将对象推送到新数组c
中。你也可以break
for循环,以避免在找到匹配后进一步不必要的循环。
var a = [{"id":"1","mark":"96"},{"id":"2","mark":"65"}];
var b = [{"student_id":"1","grade":"A"},{"student_id":"2","grade":"c"}];
var c = [];
for(var i=0; i<a.length; i++){
var objA = a[i];
for(var j=0; j<b.length; j++){
var objB = b[j];
if(objA.id === objB.student_id){
objA.grade = objB.grade;
c.push(objA);
break;
}
}
}
console.log(c);
&#13;
答案 4 :(得分:0)
假设数组"grade"
内没有a
- 对象:
let a = [{"id": "1", "mark": "96"}, {"id": "2", "mark": "65"}];
let b = [{"student_id": "1", "grade": "A"}, {"student_id": "2", "grade": "c"}];
let c =[];
for(var iterateA = 0, elA; elA = a[iterateA]; iterateA++) {
for(var iterateB = 0, elB; elB = b[iterateB]; iterateB++) {
if(elA.id === elB.student_id) {
elA['grade'] = elB.grade;
c.push(elA);
}
}
}
console.log(c);
&#13;
答案 5 :(得分:0)
这应该有效
for(var i=0; i<a.length;i++) {
for(var j = 0; j<b.length;j++) {
if(a[i].id === b[j].student_id) {
c.push({
'id': a[i].id,
'mark': a[i].mark,
'grade': b[j].grade
});
}
}
}
答案 6 :(得分:-1)
使用地图并找到
a = [{"id":"1","mark":"96"},{"id":"2","mark":"65"}];
b = [{"student_id":"1","grade":"A"},{"student_id":"2","grade":"c"}];
updatedA = a.map((val) => {
let bVal = b.find((item) => item.student_id === val.id)
if(bVal){
val.grade = bVal.grade;
}
return val;
})
console.log(updatedA);