我如何访问映射 json 数组并按 id 搜索对象并更改该对象中的值

问题描述

JSON 结构

 "applications" : [
    {
        "applicantID" : "607187fedf225c1d80cd0e7d","applicationMessage" : "bb","applicantUserName" : "alaa21","postResponse" : "still"
    },{
        "applicantID" : "6060dfde2607d52d1499c189","applicationMessage" : "ee","applicantUserName" : "taher","postResponse" : "still"
    }
],

我有“applicantID”作为参数,我想访问“applications”并找到具有“applicantID”的对象并修改该对象的字符串“postResponse”。 我正在为这个项目使用 MERN Stack

解决方法

您可以使用 .find() 数组方法完成此操作,如下所示:

const data = {
  applications: [{
      applicantID: '607187fedf225c1d80cd0e7d',applicationMessage: 'bb',applicantUserName: 'alaa21',postResponse: 'still'
    },{
      applicantID: '6060dfde2607d52d1499c189',applicationMessage: 'ee',applicantUserName: 'taher',postResponse: 'still'
    }
  ]
};

const findApplication = id => data.applications.find(a => a.applicantID === id)

console.log(findApplication('6060dfde2607d52d1499c189'));