2017-03-06 94 views
-1

我得到這個對象響應對象如何合併2對象的JavaScript

{ 
"data": [ 
    { 
     "id": "203", 
     "bench": "abc" 
    }, 
    { 
     "id": "205", 
     "bench": "def" 
    } 
], 
"responseCode": 200, 
"isSuccess": "true" 
} 

現在我想補充的響應對象上這個對象

{ 
    "id": "0", 
    "bench": "Select bench" 
} 

因此最終的對象應該看起來像這樣

{ 
"data": [ 
    { 
     "id": "0", 
     "bench": "Select bench" 
    }, 
    { 
     "id": "203", 
     "bench": "abc" 
    }, 
    { 
     "id": "205", 
     "bench": "def" 
    } 
], 
"responseCode": 200, 
"isSuccess": "true" 
} 

有沒有辦法在打字稿中做到這一點?我試過'不換',但它不起作用。

+1

'data'是一個簡單的數組,所以你所需要做的就是預先添加一個新元素......'unshift'就是這樣做的方法。 – CBroe

回答

0
response = { 
    "data": [ 
    { 
     "id": "203", 
     "bench": "abc" 
    }, 
    { 
     "id": "205", 
     "bench": "def" 
    } 
    ], 
    "responseCode": 200, 
    "isSuccess": "true" 
    }; 

    response.data.unshift({ 
    "id": "0", 
    "bench": "Select bench" 
    }); 
    console.log(response); // shows json object 
+0

@CBroe是對的,它是http://stackoverflow.com/questions/10773813/adding-something-to-the-top-of-a-json-object的副本 – RKJ