如何使用Nodejs请求补丁更新对象中的某个字段,同时保持其他字段不变



我有一个API,它返回JSON数据,如下所示:

{
"data":{
"id": "859545",
"name":"Batman",
"custom-fields": {
"--f-09":"custom-1",
"--f-10":"custom-2",
"--f-11":"custom-3"
},
"tags": [],
"created-at": "2021-09-10T15:45:16Z",
"updated-at": "2022-04-23T11:52:49Z"
}
}

对于这个JSON,我想更改字段"--f-09";至";custom1、custom-new";以及"--f-10";至";custom2、custom-new";同时保持所有其他字段与以前一样。

我知道我可以在Nodejs中使用request.PATCH,但在这种情况下,我需要再次为我希望避免的请求提供所有数据。我只想更新某些字段,同时保持其他字段不变。

在这个例子中,我提供了一个简单的例子,它只包含某些字段,但在我的实际代码中,我有很多字段,所以这是否意味着我需要再次使用所有字段构建response body json,并只更改--f-09--f-10

以下是代码:

const jsonBody = {
"data": {
"id": "859545",
"name": "Batman",
"custom-fields": {
"--f-09": "custom-1, custom-new",
"--f-10": "custom-2, custom-new",
"--f-11": "custom-2"
},
"tags": [],
"created-at": "2021-09-10T15:45:16Z",
"updated-at": "2022-04-23T11:52:49Z"
}
}

request.patch('https://reqres.in/api/users',jsonBody,function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
console.log(response.statusCode);
}
}
);

这是否意味着我需要在这里再次构建完整的JSON主体,就像我在使用PATCH时构建了上面的jsonBody一样,或者是否有其他方法可以直接传递--f-09 and --f-10的值?

首先检查,您想要更新的参数是在对象旁边。然后你可以过滤,只过滤那些值。然后可以合并对象中的单独部分。

最新更新