首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >比较两个对象并更新角度

比较两个对象并更新角度
EN

Stack Overflow用户
提问于 2020-05-06 06:40:04
回答 2查看 303关注 0票数 0

你好,我有这样的价值观

代码语言:javascript
运行
复制
const buildings = [
  { id: 111, status: false, image: 'Test1' },
  { id: 334, status: true, image: 'Test4' },
  { id: 243, status: false, image: 'Test7' },
  { id: 654, status: false, image: 'Test9' },
  { id: 222, status: true, image: 'Test8' }
];

和新的胀形

代码语言:javascript
运行
复制
const building =  { id: 222, status: false, image: 'Test2' };

您可以看到,建筑物的 id 与建筑物中的id的id相同,但现在的值状态是false图像是不同的。我所需要的是更新建筑物中的id的值,但同时也要记住,有时建筑物看起来像这样

代码语言:javascript
运行
复制
const building =  { id: 888, status: false, image: 'Test22' };

然后,我只需要更新建筑物的新身份从建筑物。我知道我可以做一个推送和比较,但我需要一个功能,为我做,将接收建筑物和建筑物,并合并它们。提前感谢

EN

回答 2

Stack Overflow用户

发布于 2020-05-06 06:56:24

您可以使用Array.find()来实现这一点,如果buildings数组与id匹配,则Find将从它返回相同的对象。您可以更新对象。如果找不到Id,则可以将新对象推入Array。

代码语言:javascript
运行
复制
const buildings = [];

function merge(building) {
  console.log('=====================================');
  console.log(`Buildings Before Merge => `, buildings);
  const found = buildings.find(({id}) => building.id === id);
  if (found) {
    Object.assign(found, building);
  } else {
    buildings.push(building);
  }
  
  console.log(`Buildings after Merge => `, buildings);
  console.log('=====================================');
}


const buildingOne =  { id: 222, status: false, image: 'Test2' }; // found will be undefined for this
const buildingOneSameId =  { id: 222, status: true, image: 'Test2Duplicate' }; // in the step, found won't be undefined.
const buildingTwo =  { id: 888, status: false, image: 'Test22' };

merge(buildingOne);
merge(buildingOneSameId);
merge(buildingTwo);

票数 0
EN

Stack Overflow用户

发布于 2020-05-06 08:48:55

您可以使用array#reduce迭代buildings,并对相同的id更新建筑物。如果不匹配,请将building追加到数组中。

代码语言:javascript
运行
复制
const buildings = [{ id: 111, status: false, image: 'Test1' },{ id: 334, status: true, image: 'Test4' },{ id: 243, status: false, image: 'Test7' },{ id: 654, status: false, image: 'Test9' },{ id: 222, status: true, image: 'Test8' }],
      firstBuilding =  { id: 222, status: false, image: 'Test2' },
      secondBuilding =  { id: 888, status: false, image: 'Test22' };

const updateBuilding = (building) => {
  let isPresent = false;
  if(buildings && buildings.length === 0) 
    return [{...building}];
    
  return buildings.reduce((r, b, i, buildings) => {
    if(b.id === building.id) {
      r.push({...building});
      isPresent = true;
    } else {
      r.push({...b});
    }
    if(!isPresent && i === buildings.length - 1) {
      r.push({...building});
    }
    return r;
  },[]);
}


console.log(updateBuilding(firstBuilding));
console.log(updateBuilding(secondBuilding));

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61628900

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档