我需要在下面的方法中修改'modelList':
fetch(fetchAddress, {
method: 'POST',
headers: {
"Content-type": "application/json; charset=UTF-8"
},
body: JSON.stringify(this.props.modelList)
})
“modelList”生成以下 JSON:
{list:[{"property1":"...","property2":"...","property3":"...","property4":"..."},{"property1":"...","property2":"...","property3":"...","property4":"..."}]}
但我需要将其发送到 API:
[{"property2":"...","property3":"..."},{"property2":"...","property3":"..."}]
修改数组或 JSON 以便发送 API 期望的内容的最佳方法是什么?
最佳答案
我猜 OP 想从每个对象中删除第一个属性。
您可以使用 Object.entries
与 Destructuring assignment然后用 Object.fromEntires
返回一个新对象:
Note that
Object.fromEntries
is "pretty" new, so you can use a simple reducer.
// {list:[{"property1":"...","property2":"...","property3":"...","property4":"..."},{"property1":"...","property2":"...","property3":"...","property4":"..."}]}
const modeList = {
list: [
{
property1: 1,
property2: 2,
property3: 3,
property4: 4
},
{
property1: 1,
property2: 2,
property3: 3,
property4: 4
}
]
};
const modified = modeList.list.map(obj => {
const [, ...rest] = Object.entries(obj);
return Object.fromEntries(rest);
});
// [{"property2":"...","property3":"..."},{"property2":"...","property3":"..."}]
console.log(modified);
关于javascript - React JS - 在 HTTP 获取中修改正文 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58696130/