0

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 ?

Kazem Ma
  • 31
  • 7

3 Answers3

1

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);
OGordo
  • 143
  • 1
  • 6
0

This method uses .filter and .map. No need for index. Just provide old name and new name:

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);
Rob Moll
  • 3,345
  • 2
  • 9
  • 15
0

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

This should do the trick

Ham
  • 1
  • 2