2017-02-16 47 views
2

我在NodeJS中調用一個函數,接收JSON對象intent,嘗試添加一個新屬性「測試」並返回該對象。問題是新的屬性「測試」永遠不會顯示在返回的對象中。但是,現有的「已處理」的值是正確更改的。有任何想法嗎?在NodeJS中向JSON對象添加新屬性

function process_first(req, res, next) { 
    Intent.getFirstUnprocessed() 
    .then(intent => { 
     intent.tested = "DONE"; 
     intent.processed = true; 
     res.json(intent); 
     }) 
    .catch(e => next(e)); 
} 

intent已初步此值:

{"processed":false,"payload":"hello","createdAt":"2017-02-16T05:07:19.596Z"} 

,並返回:

{"processed":true,"payload":"hello","createdAt":"2017-02-16T05:07:19.596Z"} 
+0

[有沒有這樣的事情作爲一個 「JSON對象」(HTTP:// benalman。 com/news/2010/03/theres-no-such-thing-as-a-json /) – Phil

+0

究竟**是什麼**意圖。它碰巧有'toJSON'方法嗎? – Phil

+0

試試這個意圖[「tested」] =「DONE」而不是intent.tested =「DONE」 –

回答

2

你的意圖對象可以是一些自定義的對象(通過像貓鼬一些庫返回)。大多數時候你不能直接修改這些對象。您必須將它們更改爲純javascript對象。這些庫爲此提供了方法(如toObject或toJSON)。此外,如果它是一個像地圖之類的集合或類似的東西,它也有toObject方法。

如果對象是一個地圖試試這個:

function process_first(req, res, next) { 
    Intent.getFirstUnprocessed() 
    .then(intent => { 
     var intenObject = intent.toObject(); 
     intenObject.tested = "DONE"; 
     intenObject.processed = true; 
     res.json(intenObject); 
     }) 
    .catch(e => next(e)); 
} 

如果它是一個JSON字符串

function process_first(req, res, next) { 
    Intent.getFirstUnprocessed() 
    .then(intent => { 
     var intenObject = JSON.parse(intent); 
     intenObject.tested = "DONE"; 
     intenObject.processed = true; 
     res.json(intenObject); 
     }) 
    .catch(e => next(e)); 
}