Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find JSON Object using multiple key/value pairs, then update that Object's other attribute

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!

like image 968
james Avatar asked Mar 18 '26 03:03

james


1 Answers

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);
like image 137
iplus26 Avatar answered Mar 19 '26 15:03

iplus26



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!