2017-01-15 42 views
0

我有一個動態表單元素,我想使用ajax保存。我將數據格式化爲javascript對象,並試圖更新每個元素。但是我無法訪問嵌套元素,所以我可以設置一個新的值。下面的結果是'未定義',但我想要做的是從數組中按數字查找一個項目,以便我可以更新數量值。訪問嵌套javascript對象

// object to hold form data for ajax submit 
var jsonLoad = { 
    type: 'estimate', 
    note: null, 
    terms: null, 
    tax: 0, 
    items: [ 
     { 
      1 : 
      { 
       description: 'test123', 
       rate: 300, 
       qty: 1 
      } 
     }, 
     { 
      2 : 
      { 
       description: 'test555', 
       rate: 600, 
       qty: 2 
      } 
     } 
    ] 
}; 

function getItem(i) { 
    jsonLoad.items.forEach(function (element) { 
     if (element[i] === i) { 
      return(element[i]); 
     } 
    }); 
} 

console.log(getItem(2)); 

回答

1

您可以檢查具有給定屬性的項目並返回該項目。

Array#some停止迭代,如果回調返回真值。

function getItem(key) { 
 
    var item; 
 
    jsonLoad.items.some(function (object) { 
 
     return item = object[key]; 
 
    }); 
 
    return item; 
 
} 
 

 
var jsonLoad = { type: 'estimate', note: null, terms: null, tax: 0, items: [{ 1: { description: 'test123', rate: 300, qty: 1 } }, { 2: { description: 'test555', rate: 600, qty: 2 } }] }; 
 

 
console.log(getItem(2));

0

這是你的答案:

// object to hold form data for ajax submit 
 
var jsonLoad = { 
 
    type: 'estimate', 
 
    note: null, 
 
    terms: null, 
 
    tax: 0, 
 
    items: [ 
 
     { 
 
      1 : 
 
      { 
 
       description: 'test123', 
 
       rate: 300, 
 
       qty: 1 
 
      } 
 
     }, 
 
     { 
 
      2 : 
 
      { 
 
       description: 'test555', 
 
       rate: 600, 
 
       qty: 2 
 
      } 
 
     } 
 
    ] 
 
}; 
 

 
function getItem(i) { 
 
    var ret = null; 
 
    jsonLoad.items.forEach(function(item){ 
 
     if(item[i]){ //if the item object has the numeric key "i" 
 
     ret = item[i]; 
 
     } 
 
    }) 
 
    return ret; 
 
} 
 

 
console.log(getItem(2));

下面是如果鍵存在檢查更識字方法:if(Object.keys(item).includes(i))