使用过滤器功能更新 JSON 中的子项目

Update subitem in JSON using filter function

我有一个 JSON 对象(包含我的扩展设置),我想在需要时更新其中的子项。 这是我搜索子项目的方式:

function GetAppByName(apps, name) {
    return apps.filter(function (app) {
        return app.name === name; 
    });
}

我发现 this way 可以更新子项的值,但我不想使用循环来查找它们,

for (var i = 0; i < jsonObj.length; i++) {
  if (jsonObj[i].Id === 3) {
    jsonObj[i].Username = "Thomas";
    break;
  }
}

如何使用过滤器或不使用 for 循环的任何方式更新 JSON 中的子项?

如果你知道项目的索引,你可以做

apps = Object.assign(apps.slice(), {[index]: {...apps[index], Username: "Thomas"}})

查找索引:

apps.findIndex((app) => app.Id === 3);

此方法使用 .filter.map。不需要 index。只需提供旧名称和新名称:

let apps = [{
    "name": "Rob",
    "age": 25
  },
  {
    "name": "Jill",
    "age": 35
  }
];

console.log("Before:", apps);

const GetAppByName = (apps, oldName, newName) => {
  apps.filter((app) => app.name === oldName)
      .map((app) => app.name = newName);
}

let result = GetAppByName(apps, "Rob", "Carl");
console.log("After", apps);

apps.map(app => (app.name === 'Rob' ? { ...app, name: 'Frank' } : app));

这应该可以解决问题