Javascript 无法使用映射功能更改数组数据

Javascript 无法使用映射功能更改数组数据,javascript,Javascript,我有data和selectedProfessional,它们是带有json对象的数组,使用相同的结构 Json obejct结构: {"id":1,"store_id":1,"united":0,"name":"Max","title":"設計師","max_booking_number":null,"price":2000,"seniority":5,"image":"https://polipoli.s3.amazonaws.com/share/professional/profession

我有data和selectedProfessional,它们是带有json对象的数组,使用相同的结构

Json obejct结构:

{"id":1,"store_id":1,"united":0,"name":"Max","title":"設計師","max_booking_number":null,"price":2000,"seniority":5,"image":"https://polipoli.s3.amazonaws.com/share/professional/professional1.jpg","desc":"Explicabo in excepturi aspernatur.","skill":"Asperiores in dicta pariatur. Illum ut ut nulla.","store_name":"FEETUP 美甲工作室","selected":true}
我想将selectedProfessional id与数据id进行比较,并将数据的参数更改为SelectedTrue或false

这是我的密码:

const { data } = response;
  console.log('first data', data);
  console.log('selectedProfessional', selectedProfessional);
  data.map(option => {
    selectedProfessional.map(value => {
      if (value.id === option.id) {
        console.log('1');
        option.selected = true;
      } else {
        option.selected = false;
      }
    });
  });
  console.log('final data', data);
以下是打印结果:

我认为我最终选择的数据ID1和ID2对象应该是真的,但只有ID2是真的


我不知道为什么。

您可以返回一个新数组,其中包含一个更新的选定标志,其中id位于selectedProfessional数组中:


以下是实现这一目标的可读且有效的方法

常量数据=[ {id:1,store_id:1,otherAttr:…,selected:true}, {id:2,store_id:2,otherAttr:…,selected:true}, {id:3,store_id:3,otherAttr:…,selected:true}, {id:4,store_id:4,otherAttr:…,selected:true} ]; const selectedProfessional=[ {id:2,otherAttr:…}, {id:4,otherAttr:…} ]; 让newData=data.mapoption=>{ //确保最初未选择选项 option.selected=false; 让isFoundInSelectedProfessional=selectedProfessional.somesp=>sp.id==option.id; 如果未选择专业人士{ console.log`id${option.id}选择为true`; option.selected=true; } 返回选项 };
console.log'final data',newData;数据是否默认将所选属性设置为false?删除else{…}块并使用fine;谢谢大家,删除其他{…}正在工作,我知道我现在的问题是什么。谢谢你的回答,它工作了!我现在发现了我的问题。
updatedData = data.map(option => selectedProfessional.map(v => v.id).indexOf(option.id) > -1 ? {
   ...option,
   selected: true
} : option);

console.log( updatedData );