How to extract a json object that's inside a json object

前端 未结 3 1245
暖寄归人
暖寄归人 2021-02-04 12:16

Convert this:

{\"items\":[{\"id\":\"BLE89-A0-123-384\",\"weight\":\"100\",\"quantity\":3},
          ...    
          {\"id\":\"BLE10-A0-123-321\",\"weight\":\"         


        
3条回答
  •  天涯浪人
    2021-02-04 12:45

    You can try with:

    var obj = {
        "items":[
            {"id":"BLE89-A0-123-384","weight":"100","quantity":3},
            {"id":"BLE10-A0-123-321","weight":"100","quantity":4}
        ],
        "country":"JUS",
        "region":"A",
        "timeout":"FILLER"
    };
    
    var quantities = {};
    obj.items.forEach(function (item) {
        quantities[item.id] = item.quantity;
    });
    

    quantities will then be the object {"BLE89-A0-123-384":3,"BLE10-A0-123-321":4}. forEach is a native method of array objects in JavaScript that lets you iterate through their elements. You may want to put that piece of code inside a function:

    function getQuantities(obj) {
        var quantities = {};
        obj.items.forEach(function (item) {
            quantities[item.id] = item.quantity;
        });
        return quantities;
    }
    

提交回复
热议问题