使用多个键/值对查找JSON对象,然后更新该对象的其他属性 [英] Find JSON Object using multiple key/value pairs, then update that Object's other attribute
本文介绍了使用多个键/值对查找JSON对象,然后更新该对象的其他属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出
sessionStorage.cart = "[
{"id":121,"name":"Pants","number":1,"specification":""},
{"id":121,"name":"Pants","number":2,"specification":""},
{"id":121,"name":"Pants","number":3,"specification":""}
]"
我想编写一个函数,查找ID为121,裤子名称,数字2的对象,以便我可以更新该对象的规格.因此,我将传递id,名称,数字和所需的新规范值,并获得以下结果:
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!
推荐答案
使用此:
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);
这篇关于使用多个键/值对查找JSON对象,然后更新该对象的其他属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文