Given
sessionStorage.cart = "[
{"id":121,"name":"Pants","number":1,"specification":""},
{"id":121,"name":"Pants","number":2,"specification":""},
{"id":121,"name":"Pants","number":3,"specification":""}
]"
I'd like to write a function that finds the object with id of 121, name of Pants, number of 2, so that I can update that object's specification. So I would pass the id, the name, the number, and the desired new specification value, and get an output of this:
sessionStorage.cart = "[
{"id":121,"name":"Pants","number":1,"specification":""},
{"id":121,"name":"Pants","number":2,"specification":"new value"},
{"id":121,"name":"Pants","number":3,"specification":""}
]"
Am really struggling on thinking this one through... guidance welcome!
Use this:
var cart = [
{
"id": 121,
"name": "Pants",
"number": 1,
"specification": ""
},
{
"id": 121,
"name": "Pants",
"number": 2,
"specification": ""
},
{
"id": 121,
"name": "Pants",
"number": 3,
"specification": ""
}
];
cart.forEach(function(entry) {
if (entry.id == 121 && entry.name == 'Pants' && entry.number == 2) {
entry.specification = 'new value';
}
});
console.log(cart);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With