使用多个键/值对查找JSON对象,然后更新该对象的其他属性

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

本文关键字:对象 然后 更新 属性 其他 JSON 查找      更新时间:2023-09-26

给定

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,名称为Pants,编号为2的对象,以便我可以更新该对象的规范。因此,我将传递id、名称、数字和所需的新规格值,并得到如下输出:

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":""}
]"

我真的在努力思考这个问题…欢迎指导!

使用

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);

使用Array.prototype.find的简单解决方案

sessionStorage.cart.find(e => 
  e.id     === 121     &&
  e.name   === 'Pants' &&
  e.number === 2
).specification = 'new value';
console.log(JSON.stringify(sessionStorage.cart, null, '  '));

输出
[
  {
    "id": 121,
    "name": "Pants",
    "number": 1,
    "specification": ""
  },
  {
    "id": 121,
    "name": "Pants",
    "number": 2,
    "specification": "new value"
  },
  {
    "id": 121,
    "name": "Pants",
    "number": 3,
    "specification": ""
  }
]

您可能想要尝试下面的代码:

function update(oldValues, newValues, keyToCompare) {
    var keyToCompareLen = keyToCompare.length;
    var result = [];
    oldValues.forEach(function(oldValue){
        newValues.forEach(function(newValue){
            var cnt = 0;
            keyToCompare.forEach(function(key){
                if(newValue[key] == oldValue[key]) {
                    ++cnt;
                }
            });
            if(cnt == keyToCompareLen) {
                oldValue = $.extend(true, {}, oldValue, newValue);
            }
        });
        result.push(oldValue);
    });
    return result;
}
var result = update([
  {"id":121,"name":"Pants","number":1,"specification":""},
  {"id":121,"name":"Pants","number":2,"specification":""},       
  {"id":121,"name":"Pants","number":3,"specification":""}
], [
  {"id":121,"name":"Pants","number":2,"specification":"test"}
], [
  "id",
  "name",
  "number"
]);
console.log(result);

注意:您需要包含jquery库。您也可以在这里运行代码https://fiddle.jshell.net/b17fx6qk/1/

遍历数组的效率很低。为了提高性能,您可以将所有索引值字符串化,并使用它们将对象存储在hashmap中,以便快速查找。比如:

function cartItem() {
  this.id;
  this.name;
  this.number;
  this.specification;
}
CartItem.hash = function(id, name, number) {
  return [id, name, number].join('|');
};
cartItem.prototype.toHash = function() {
  return CartItem.hash(this.id, this.name, this.number);
};
var cartMap = cart.reduce(function(map, item) {
  var key = item.toHash();
  map[key] = item;
}, { });

然后你可以(非常快速地)通过它的哈希值查找项目:

cartMap[CartItem.hash(id, name, number)];

试一下。只需匹配和更新

$(document).ready(function() {
  var o = [];
  o.id = 121;
  o.name = "Pants";
  o.number = 2;
  updateVal(o);
});
function updateVal(o) {
  var cart = [{
    "id": 121,
    "name": "Pants",
    "number": 1,
    "specification": ""
  }, {
    "id": 121,
    "name": "Pants",
    "number": 2,
    "specification": ""
  }, {
    "id": 121,
    "name": "Pants",
    "number": 3,
    "specification": ""
  }];
  $.each(cart, function(a, b) {
    if (b.id == o.id && b.name == o.name && b.number == o.number) {
      b.specification = "new value";
    }
  });
  alert("value updated. specification:" + cart[1].specification);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>