たとえば、私はこの技術をバスケット機能で使用しています。
新しいアイテムをバスケットに追加しましょう。バスケットにいくつかのアイテムを追加した後
var productArray=[];
$(document).on('click','[cartBtn]',function(e){
e.preventDefault();
$(this).html('<i class="fa fa-check"></i>Added to cart');
console.log('Item added ');
var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image'), "quantity":1, "discount":0, "total":$(this).attr('pr_price')};
if(localStorage.getObj('product')!==null){
productArray=localStorage.getObj('product');
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
else{
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
itemCountInCart(productArray.length);
});
は - バスケットからいくつかのアイテムを除去するためのこの
[
{
"id": "95",
"nameEn": "New Braslet",
"price": "8776",
"image": "1462.jpeg",
"quantity": 1,
"discount": 0,
"total": "8776"
},
{
"id": "96",
"nameEn": "new braslet",
"price": "76",
"image": "1462012431497.jpeg",
"quantity": 1,
"discount": 0,
"total": "76"
},
{
"id": "97",
"nameEn": "khjk",
"price": "87",
"image": "1462012483421.jpeg",
"quantity": 1,
"discount": 0,
"total": "87"
}
]
等JSON配列を生成します。
$(document).on('click','[itemRemoveBtn]',function(){
var arrayFromLocal=localStorage.getObj('product');
findAndRemove(arrayFromLocal,"id",$(this).attr('basketproductid'));
localStorage.setObj('product', arrayFromLocal);
loadBasketFromLocalStorageAndRender();
});
//This function will remove element by specified property. In my case this is ID.
function findAndRemove(array, property, value) {
array.forEach(function(result, index) {
if(result[property] === value) {
//Remove from array
console.log('Removed from index is '+index+' result is '+JSON.stringify(result));
array.splice(index, 1);
}
});
}
最後に、「JSを使用してJSONオブジェクトを更新する」という質問の本当の答えです。私の例では、「数」要素の値を変更する際に、製品数量と合計価格を更新します。
$(document).on('keyup mouseup','input[type=number]',function(){
var arrayFromLocal=localStorage.getObj('product');
setQuantityAndTotalPrice(arrayFromLocal,$(this).attr('updateItemid'),$(this).val());
localStorage.setObj('product', arrayFromLocal);
loadBasketFromLocalStorageAndRender();
});
function setQuantityAndTotalPrice(array,id,quantity) {
array.forEach(function(result, index) {
if(result.id === id) {
result.quantity=quantity;
result.total=(quantity*result.price);
}
});
}
JSONはJavaScriptオブジェクト表記の略です。これは、jsが非常に簡単に理解できるものです。あなたの質問はJSONを扱っていません。これは純粋にjsオブジェクト操作を扱います。 「Javascriptを使用してJSONオブジェクトを更新する」は、「Javascriptを使用してJavascriptオブジェクトを更新する」に変換されるため、moot式です。 – Zirak
Zirak、あなたはパーティーで楽しくなければなりません – stef