如何PUT到JSON数组中的某个对象(npm请求)

时间:2016-05-27 22:00:23

标签: javascript json node.js npm

我基本上尝试使用请求模块的PUT请求在JSON数组中设置值。该数组有多个主要对象,我只想将其设置为其中一个。它采用以下格式:

[
   0: {
           status: 'pending'
       }
   1: {
           status: 'pending'
       }
 ]

我正在使用来自  npm请求的示例脚本'文档:

request({
method: 'PUT',
preambleCRLF: true,
postambleCRLF: true,
uri: 'http://service.com/upload',
multipart: [
  {
    'content-type': 'application/json',
    body: JSON.stringify(-what-goes-in-here-?-
  }
],
function (error, response, body) {
if (error) {
  return console.error('upload failed:', error);
}
console.log('Upload successful!  Server responded with:', body);
 })

所以最大的问题是我应该放入什么"身体:"比如0:{状态:'已批准'}而不是1:{状态:'已批准'}

我感谢任何帮助,如果需要,我可以详细说明。 :)

1 个答案:

答案 0 :(得分:0)

假设您将在body对象中传递2件事。

{
  index: 0, // i.e., object index in array
  status: 'approved' // i.e., status to update
}

现在,您必须拥有upload路由处理程序,例如。

app.put('/upload', function(req, res) {
  var index = req.body.index,
      status = req.body.status;

  // update status in your data (Array); 
  // let's say your array is `data`
  data[index].status = status;  // updated.

  res.send('success'); // etc.
})