如何解决JS更新数组中的对象按值匹配
具有第一个数组(a)和第二个具有更新的值(b)。需要通过ID对象更新匹配并获取结果数组(c)。如何使它变得简单快捷?
dim i as int
for i= 17 to 31
If ActiveSheet.Range("B" & i).EntireRow.Hidden = False Then
If Range("C" & i).Value = "" Then
With Range("C" & i & ":E" & i)
.Locked = False
.Merge
.HorizontalAlignment = xlCenterAcrossSelection
.VerticalAlignment = xlCenter
End With
With Range("F" & i & ":G" & i)
.Locked = False
.Merge
.HorizontalAlignment = xlCenterAcrossSelection
.VerticalAlignment = xlCenter
End With
With Range("H" & i & ":J" & i)
.Locked = False
.Merge
.HorizontalAlignment = xlCenterAcrossSelection
.VerticalAlignment = xlCenter
End With
End If
End If
next i
解决方法
我建议您创建一个对象,其中键是用于快速访问的ID。
使用新创建的对象,您可以使用b
作为键,从id
访问特定对象并更新对象。
最后,使用函数c
获得数组Object.values
。
这是假设b
具有a
中存在的ID。
let a = [ { id: 1,activated: '0' },{ id: 2,{ id: 3,{ id: 4,activated: '0' }]
let b = [ { id: 2,activated: '1' },activated: '1' }];
let newA = a.reduce((a,{id,...rest}) => ({...a,...{[id]: {id,...rest}}}),{});
b.forEach(({id,activated}) => newA[id].activated = activated);
let c = Object.values(newA);
console.log(c);
.as-console-wrapper { max-height: 100% !important; top: 0; }
,
您可以使用Array.map,然后使用foreach对象,可以使用Array.find通过ID检查它是否存在于arrayB中,并返回是否存在。
let a = [
{ id: 1,];
let b = [
{ id: 2,];
const c = a.map(e => {
let newValue = b.find(n => e.id === n.id);
if (!!newValue) {
return newValue;
}
return e;
});
,
这是我的处理方式:
function mergeArray(...toMerge) {
let output = {};
toMerge.forEach(arr => {
arr.forEach(item => {
output[item.id] = item;
});
});
return Object.values(output);
}
let a = [
{ id: 1,];
let b = [
{ id: 2,];
console.dir(mergeArray(a,b)) // can merge n-number of arrays.
,
let c = a.map( aObj => {
let found = b.find(bObj => bObj.id === aObj.id);
if(found) return found;
else return aObj;
});
,
您可以创建由id
键控的第二个数组的映射,然后将a
个对象复制到c
中时,使用该映射合并匹配的{{ 1}}个对象。
b
let a = [{ id: 1,activated: '0' }]
let b = [{ id: 2,activated: '1' }];
let map = new Map(b.map(o => [o.id,o]));
let c = a.map(o => ({...o,...map.get(o.id)}));
console.log(c);
,
根据数组a的ID构建哈希。通过在散列中查找索引b.id来遍历数组b,如果发现该属性在具有已建立索引的a中实现,则激活该属性。否则(例如id:5)在旧数组中不存在该id的条目,因此请创建一个新条目并实现散列。
let a = [
{ id: 1,{ id: 5,];
let hash = a.flatMap(el => el.id);
b.forEach(elem => {
index = hash.indexOf(elem.id);
if (index!=-1)
a[index].activated=elem.activated;
else {
a.push(elem);
hash.push(elem.id);
}
});
console.log(a);
,
尝试一下
let a = [{
id: 1,activated: '0'
},{
id: 2,{
id: 3,{
id: 4,]
let b = [{
id: 2,activated: '1'
},]
//Result array:
c = [{
id: 1,]
let result = a.map(e => {
let p = b.find(be => be.id === e.id)
if (p) e.activated = p.activated;
return e
})
console.log(result)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。