Here is a JSON data structure that I am working with:
var jsonData = [
{
"id": "1",
"key1": "Name1",
"key2": 2,
"key3": 1
},
{
"id": "2",
"key1": "Name2",
"key2": 2,
"key3": 1
},
{
"id": "3",
"key1": "Name3",
"key2": 2,
"key3": 1
}
]
I have a requirement to replace one object with another within this array. For example, I need to update:
{
"id": "2",
"key1": "Name2",
"key2": 2,
"key3": 1
}
with
{
"id": "5",
"key1": "Name7",
"key2": 3,
"key3": 2
}
At the moment, I am able to filter out the specific object from the array:
var idToReplace = 2;
var newObj = {"id": "5", "key1": "Name7", "key2": 3, "key3": 2};
var filteredData = jsonData.filter(function(element) {
return element.id === idToReplace;
});
console.log(filteredData);
What steps should be taken next in order to replace an object with id === 2
with the newObj
?