2012-01-02 30 views
30

javascriptまたはJqueryを使用して次のJSONオブジェクトを動的に更新するにはどうすればよいですか?Javascriptを使用したJSONオブジェクトの更新

var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'}, 
       {'Id':'2','Username':'Steve','FatherName':'Johnson'}, 
       {'Id':'3','Username':'Albert','FatherName':'Einstein'}] 

「Id」が「3」の場合、ユーザー名を「Thomas」に動的に更新したいと考えています。

これはどのように達成できますか?

+7

JSONはJavaScriptオブジェクト表記の略です。これは、jsが非常に簡単に理解できるものです。あなたの質問はJSONを扱っていません。これは純粋にjsオブジェクト操作を扱います。 「Javascriptを使用してJSONオブジェクトを更新する」は、「Javascriptを使用してJavascriptオブジェクトを更新する」に変換されるため、moot式です。 – Zirak

+22

Zirak、あなたはパーティーで楽しくなければなりません – stef

答えて

52

JavaScriptの溶液無地:対応するユーザー名を設定し、それが一致するIDを探して上

ループ、及びループからbreak一致アイテムが変更された後:

for (var i = 0; i < jsonObj.length; i++) { 
    if (jsonObj[i].Id === 3) { 
    jsonObj[i].Username = "Thomas"; 
    break; 
    } 
} 

Here it is on jsFiddle.

関数にラップされた同じものは次のとおりです。

function setUsername(id, newUsername) { 
    for (var i = 0; i < jsonObj.length; i++) { 
    if (jsonObj[i].Id === id) { 
     jsonObj[i].Username = newUsername; 
     return; 
    } 
    } 
} 

// Call as 
setUsername(3, "Thomas"); 
+1

上記のソリューションはフィドラーで動作します。私はjsonの文字列を質問にして、ASP.NET MVC 5 Razorビューで動作させるためにobj = JSON.parse(jsonObj)を使用してjsonに文字列を解析しなければなりませんでした。操作する前に。誰かを助けることを願っています。 Btw私は解決策が働くのでupvoted。 – user2330678

+0

これは素晴らしい解決策です。私は以下の答えでもう少しそれを取った。 –

6

リストを反復処理して、各オブジェクトのプロパティを確認します。

for (var i = 0; i < jsonObj.length; ++i) { 
    if (jsonObj[i]['Id'] === '3') { 
     jsonObj[i]['Username'] = 'Thomas'; 
    } 
} 
1

使用:

var parsedobj = jQuery.parseJSON(jsonObj); 

あなたは、文字列に滞在する形式を必要としない場合にのみ有用であろう。 それ以外の場合は、JSONライブラリを使用してこれをJSONに変換する必要があります。

2
var i = jsonObj.length; 
while (i --> 0) { 
    if (jsonObj[i].Id === 3) { 
     jsonObj[ i ].Username = 'Thomas'; 
     break; 
    } 
} 

あるいは、配列は常にIDによって注文された場合:

jsonObj[ 2 ].Username = 'Thomas'; 
2

JSONはJavaScriptのオブジェクト記法です。 JSONオブジェクトのようなものはありません。 JSONはJavaScriptオブジェクトをテキストで表現する単なる方法です。

これで、in-memory JavaScriptオブジェクトを更新する方法があります。 qiao's answerは、これを簡単に行う方法を示しています。

4
$(document).ready(function(){   
    var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'}, 
       {'Id':'2','Username':'Steve','FatherName':'Johnson'}, 
       {'Id':'3','Username':'Albert','FatherName':'Einstein'}]; 

    $.each(jsonObj,function(i,v){  
     if (v.Id == 3) { 
     v.Username = "Thomas"; 
     return false; 
     } 
    }); 

alert("New Username: " + jsonObj[2].Username); 

}); 
1

たとえば、私はこの技術をバスケット機能で使用しています。

新しいアイテムをバスケットに追加しましょう。バスケットにいくつかのアイテムを追加した後

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

} 
0

私は遠くMichael Berkowski年代は、ステップ(または2)を答える取り、任意のルックアップフィールドと任意のターゲットフィールドを許可する、より柔軟な機能を作成しました。楽しみのために私は誰かがすべてを置き換えることを望むかもしれない場合にはスプラット(*)能力をそこに投げた。 jQueryは必要ありません。 checkAllRowsを使用すると、検索結果から検索を中断するオプションや、前述のすべての置換えを行うことができます。あなたのデータと

function setVal(update) { 
    /* Included to show an option if you care to use jQuery 
    var defaults = { jsonRS: null, lookupField: null, lookupKey: null, 
     targetField: null, targetData: null, checkAllRows: false }; 
    //update = $.extend({}, defaults, update); */ 

    for (var i = 0; i < update.jsonRS.length; i++) { 
     if (update.jsonRS[i][update.lookupField] === update.lookupKey || update.lookupKey === '*') { 
      update.jsonRS[i][update.targetField] = update.targetData; 
      if (!update.checkAllRows) { return; } 
     } 
    } 
} 


var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'}, 
      {'Id':'2','Username':'Steve','FatherName':'Johnson'}, 
      {'Id':'3','Username':'Albert','FatherName':'Einstein'}] 

あなたは次のように使用します。

var update = { 
    jsonRS: jsonObj, 
    lookupField: "Id", 
    lookupKey: 2, 
    targetField: "Username", 
    targetData: "Thomas", 
    checkAllRows: false 
    }; 

setVal(update); 

とボブのあなたのおじさん。 :) [偉大な作品]

関連する問題