programing

Javascript를 사용하여 JSON 개체 업데이트

goodcopy 2023. 3. 19. 20:20
반응형

Javascript를 사용하여 JSON 개체 업데이트

javascript 또는 Jquery를 사용하여 다음 JSON 개체를 동적으로 업데이트하려면 어떻게 해야 합니까?

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

사용자 이름을 'Id'가 '3'인 'Thomas'로 동적으로 업데이트하고 싶습니다.

어떻게 하면 좋을까요?

플레인 JavaScript 솔루션(전제:jsonObjJSON이 이미 포함되어 있습니다.

그 위에서 일치하는 ID를 찾아 대응하는 사용자 이름을 설정하고, 대응하는 사용자 이름을 설정하고,break일치하는 항목이 수정된 후 루프에서 다음을 수행합니다.

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

여기 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");

목록을 반복한 후 각 개체의 속성을 확인합니다.

for (var i = 0; i < jsonObj.length; ++i) {
    if (jsonObj[i]['Id'] === '3') {
        jsonObj[i]['Username'] = 'Thomas';
    }
}
$(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);

});

용도:

var parsedobj = jQuery.parseJSON( jsonObj);

이 기능은 문자열을 유지하기 위해 형식이 필요하지 않은 경우에만 유용합니다.그렇지 않으면 JSON 라이브러리를 사용하여 다시 JSON으로 변환해야 합니다.

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

또는 어레이가 항상 ID로 정렬되어 있는 경우:

jsonObj[ 2 ].Username = 'Thomas';

JSON은 JavaScript 객체 표기법입니다.JSON 오브젝트는 존재하지 않습니다.JSON은 JavaScript 개체를 텍스트로 표현하는 한 가지 방법입니다.

인메모리 JavaScript 오브젝트를 갱신하는 방법이 필요합니다.Qiao의 답변은 그것을 어떻게 해야 하는지 충분히 단순하게 보여준다.

Michael Berkowski의 답변을 한 걸음 또는 두 걸음 더 나아가 검색 필드 및 대상 필드를 모두 허용하는 보다 유연한 기능을 만들었습니다.재미삼아 스플래트(*) 기능을 삽입했습니다.누군가 모두 교환하고 싶어할까 봐.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);

밥은 삼촌이잖아요.[잘해요]

예를 들어 바스켓 기능에서 이 기술을 사용하고 있습니다.

새로운 아이템을 장바구니에 추가합니다.

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

});

아이템을 바구니에 추가한 후 - 다음과 같은 json 어레이를 생성합니다.

[
    {
        "id": "95",
        "nameEn": "New Braslet",
        "price": "8776",
        "image": "1462012394815.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"
    }
]

카트에서 일부 아이템을 제거하는 데 사용됩니다.

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

}

나는 이것이 루프보다 더 효율적인 방법이라고 생각한다.

1-첫 번째 항목 색인 찾기.-2초 동안 정확한 요소를 편집합니다.(존재하지 않는 경우 추가)

예:

let index= jsonObj.findIndex(x => x["Id"] === 3); 
if (index == -1) {
 // add
 jsonObj.push({ id:3, .... });
 } else {
  // update
   jsonObj[index]["Username"]="xoxo_gossip_girl"
 }
    var jsonObj = [{'Id':'1','Quantity':'2','Done':'0','state':'todo',
        'product_id':[315,"[LBI-W-SL-3-AG-TA004-C650-36] LAURA BONELLI-WOMEN'S-SANDAL"],
        'Username':'Ray','FatherName':'Thompson'},  
          {'Id':'2','Quantity':'2','Done':'0','state':'todo',
          'product_id':[314,"[LBI-W-SL-3-AG-TA004-C650-36] LAURA BONELLI-WOMEN'S-SANDAL"],
          'Username':'Steve','FatherName':'Johnson'},
          {'Id':'3','Quantity':'2','Done':'0','state':'todo',
          'product_id':[316,"[LBI-W-SL-3-AG-TA004-C650-36] LAURA BONELLI-WOMEN'S-SANDAL"],
          'Username':'Albert','FatherName':'Einstein'}];

          for (var i = 0; i < jsonObj.length; ++i) {
            if (jsonObj[i]['product_id'][0] === 314) {


                this.onemorecartonsamenumber();


                jsonObj[i]['Done'] = ""+this.quantity_done+"";

                if(jsonObj[i]['Quantity'] === jsonObj[i]['Done']){
                  console.log('both are equal');
                  jsonObj[i]['state'] = 'packed';
                }else{
                  console.log('not equal');
                  jsonObj[i]['state'] = 'todo';
                }

                console.log('quantiy',jsonObj[i]['Quantity']);
                console.log('done',jsonObj[i]['Done']);


            }
        }

        console.log('final',jsonObj);
}

quantity_done: any = 0;

  onemorecartonsamenumber() {
    this.quantity_done += 1;
    console.log(this.quantity_done + 1);
  }

//json 값을 업데이트하여 json 개체에 푸시

    var sales1 = [];
if (jsonObj && Object.keys(jsonObj ).length != 0) {
        jsonObj .map((value) => {
            const check = sales1.filter(x => x.order_date === String(value.order_date).substring(0, 10))
            if (check.length) {
                sales1.filter(x => x.sale_price = Number(x.sale_price) + Number(value.sale_price))
            } else {
                let data = { "sale_price": Number(value.sale_price), "order_date": String(value.order_date).substring(0, 10) }
                sales1.push(data)
            }
        })
    }

다음을 사용하여 사용자 이름을 'Id'가 '3'인 'Thomas'로 동적으로 업데이트할 수 있습니다.

jsonObj.find(i=>i.Id===3).Username='Thomas'

언급URL : https://stackoverflow.com/questions/8702474/updating-a-json-object-using-javascript

반응형