Search code examples
javascriptjquerygoogle-chrome-extension

Update subitem in JSON using filter function


I've a JSON object (that contains my extension's settings) and I want to update subitems inside it when needed. This is the way I'm searching for subitems:

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

I found this way to update the values of subitems but I don't want to use loops to find them,

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

How can I update a subitem in my JSON using filter or any way without a for loop ?


Solution

  • If you know the index of the item, you can do

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

    Find the index with:

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