JS:如何根据对象属性更改对象属性的值

时间:2018-10-03 18:09:55

标签: javascript json rest typescript ecmascript-6

我有这样的JSON数据:

inputData = [
{ id : 179849, name : alex , lastname: sanchez},
{ id : 788539, name : Paul, lastname: bearer},
{ id : 282169, name : Jean, lastname: nobel},
...
{ id : 632785, name : Maria, lastname: parak}
]

我需要根据其 id (例如:788539)

搜索某个对象

并更改其名称属性的值  -> 名称变为:bruno

数据将变为:

resultData= [
{ id : 179849, name : alex , lastname: sanchez},
{ id : 788539, name : bruno, lastname: bearer},  /* THIS ONE*/
{ id : 282169, name : Jean, lastname: nobel},
...
{ id : 632785, name : Maria, lastname: parak}
]

过滤/映射数据以进行此类修改的最简单方法是什么?

2 个答案:

答案 0 :(得分:3)

resultData= [
{ id : 179849, name : alex , lastname: sanchez},
{ id : 788539, name : bruno, lastname: bearer},  /* THIS ONE*/
{ id : 282169, name : Jean, lastname: nobel},
...
{ id : 632785, name : Maria, lastname: parak}
];

id = 788539;

resultData.forEach(ele=>{
    if(ele.id == id){
    ele.name = 'bruno'
    }
});

console.log(resultData);

答案 1 :(得分:1)

某些替代方案,Felix Kling提到的替代方案可能需要polyfill

// Mentioned by Felix Kling 
inputData.find(x => x.id === 788539)
  .name = 'Bruno'

您也可以使用for of

for (let item of inputData) {
  if (item.id === 788539) {
    item.name = 'Bruno'
    break
  }
}