我希望这不是重复。我必须为请求准备POST数据。 预期的工作机构格式如下:
{
"type": "expense",
"field_date_cost": {
"und": [{
"value": {
"date": "16/04/2018"
}
}]
},
"field_amount": {
"und": [{
"value": "10"
}]
},
"field_details": {
"und": [{
"value": "test"
}]
}
}
我的HTTP POST请求现在以此格式从表单接收数据。
{
"field_date_cost": "05/03/2018",
"field_amount": "10",
"field_details": "test",
"type": "expense"
}
我使用下面的代码(ES6)收集数据。
const field_date_cost = document.querySelector('#edit-date').value;
const field_amount = document.querySelector('#edit-amount').value;
const field_details = document.querySelector('#edit-details').value;
const id = document.querySelector('#id').value;
const type = "expense";
const data = {
field_date_cost,
field_amount,
field_details,
type
}
}
我想修改JS中的每个元素以匹配所需的结构。我尝试了Array.prototype.map
和其他人。
答案 0 :(得分:1)
只需创建一个具有所需格式的对象,然后将变量插入适当的位置:
const field_date_cost = "05/03/2018";
const field_amount = '10';
const field_details = 'test';
const type = "expense";
const body = {
"type": type,
"field_date_cost": {
"und": [{
"value": {
"date": field_date_cost
}
}]
},
"field_amount": {
"und": [{
"value": field_amount
}]
},
"field_details": {
"und": [{
"value": field_details
}]
}
};
console.log(body);