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

3

鉴于

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

我真的在思考这个问题...欢迎指导!


1
尝试从 forif 开始。 - zerkms
问题在于示例中使用了数组,而不是 JSON,这使得下面的答案不正确。 - obreezy
5个回答

5
使用这个:

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


1

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

注意:这需要ES6。

0

尝试这样做。只需匹配和更新即可。

$(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>


0
你可能想尝试这段代码:
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/


我认为仅在一个地方使用jQuery.extend()方法而不在其他地方使用jQuery有点过了。 - iplus26
@iplus26,这没问题,因为他/她已经在使用jQuery库了。 - Neil Villareal
不,不,不。别误会。我只想讨论何时使用jQuery......这与个人无关,抱歉... - iplus26

0

遍历数组可能效率低下。为了提高性能,您可以将所有索引值转换为字符串,并使用它们来存储对象在哈希表中以便快速查找。类似这样:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接