2016-10-12 119 views
0

我有下面的JS對象,我需要用request.rules[0]推另一個類似的對象。如何在使用Javascript的對象數組中添加對象

request : [ 
    rules: 
    [ 
    { 
     pageFilters: 
     [ 
     { 
      matchType: 'contains', 
      type: 1, 
      value: 'a' 
     }, 
     { 
      matchType: 'does not contain', 
      type: 1, 
      value: 'b' 
     } 
     ], 
     name: 'TEST' 
    } 
    ] 
] 

這是我需要推到request.rules [1]對象:

{ 
    pageFilters: 
    [ 
    { 
     matchType: 'contains', 
     type: 1, 
     value: 'c' 
    }, 
    { 
     matchType: 'does not contain', 
     type: 1, 
     value: 'd' 
    } 
    ], 
    name: 'TEST 2' 
} 

這就是我試圖實現,但它不工作...

request.rules[1].pageFilters[0].push({ 
    matchType: 'contains', 
    type: 1, 
    value: 'c' 
}) 
request.rules[1].pageFilters[1].push({ 
    matchType: 'contains', 
    type: 1, 
    value: 'd' 
}) 
request.rules[1].name = "TEST 2"; 

這是預期的結果:

request :[ 
    rules: 
    [ 
    { 
     pageFilters: 
     [ 
     { 
      matchType: 'contains', 
      type: 1, 
      value: 'a' 
     }, 
     { 
      matchType: 'does not contain', 
      type: 1, 
      value: 'b' 
     } 
     ], 
     name: 'TEST' 
    }, 
    { 
     pageFilters: 
     [ 
     { 
      matchType: 'contains', 
      type: 1, 
      value: 'c' 
     }, 
     { 
      matchType: 'does not contain', 
      type: 1, 
      value: 'd' 
     } 
     ], 
     name: 'TEST 2' 
    } 
    ] 
] 
+0

是請求一個數組? – Weedoze

+0

只需創建一個新對象,然後執行'request.rules.push(newObj)' – vlaz

+0

request.rules似乎只有一個元素,不是嗎? – Sergeon

回答

0

不必推到一個特定的位置例如request.rules [1] .pageFilters [0],而是在陣列本身這樣

var anotherFilter = { 
    matchType=contains, 
    type=1, 
    value=c 
}; 

request.rules[1].pageFilters.push(anotherFilter); 
+0

我已經試過了,它返回我:'TypeError:無法從undefined'讀取屬性「pageFilters」 – Valip

0

以適當的對象與請求作爲對象,

request: { // should be an object, not an array 
    rules: [ 

你可以只使用

var object1 = { request: { rules: [{ pageFilters: [{ matchType: 'contains', type: 1, value: 'a' }, { matchType: 'does not contain', type: 1, value: 'b' }], name: 'TEST' }] } }, 
 
    object2 = { pageFilters: [{ matchType: 'contains', type: 1, value: 'c' }, { matchType: 'does not contain', type: 1, value: 'd' }], name: 'TEST 2' }; 
 
      
 
object1.request.rules.push(object2); 
 
    
 
console.log(object1);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+0

對不起!我的代碼由Google Script控制檯格式化,我將對其進行編輯。 – Valip

-2

我明白你代碼, { 使用MatchType =含有 類型= 1, 值= C } 我看到 { 類型:1, 值:C }

相關問題