我这个component.后面的东西是遍历出来的,不是写死的 我又该如何写
时间: 2024-02-19 09:03:35 浏览: 17
如果 `component` 属性名是动态生成的,你可以使用中括号语法来动态添加属性。具体代码如下:
```
const data = {
"blackListTitle": "黑名单1",
"severity": 2,
"applicationScope": "",
"status": 0,
"blackListNote": "黑名单1备注",
"component": {}
};
// 遍历 component 对象,动态添加子属性
const component = {
"dI5zOD7qQ6ObUHAnlDylSa": ["aCg9yxtMk7X8PwV9wSPPZM", "aDi3fii6QbqbLmJ_YdzIrM"],
"1ZHFNZgQQgW81yjcAZXY3w": ["cNmmtm-wA3s9d6OZdh1ilv"]
};
for (const key in component) {
if (component.hasOwnProperty(key)) {
data.component[key] = component[key];
}
}
// 将对象转换为 JSON 字符串
const jsonString = JSON.stringify(data);
// 发送 POST 请求
fetch(url, {
method: 'POST',
body: jsonString,
headers: {
'Content-Type': 'application/json'
}
}).then(response => {
// 处理响应
}).catch(error => {
// 处理错误
});
```
在上面的代码中,我先给 `data` 对象添加了一个名为 `component` 的空对象。然后遍历 `component` 对象,将其子属性动态添加到 `data.component` 对象中。最后将对象转换为 JSON 字符串并发送 POST 请求。