新手问题:有没有更好的方法在Angular中构造json对象?目前我只能做以下事情:
var fieldName1 = 'name1';
var fieldValue1 = 'value1';
var fieldName2 = 'name2';
var fieldValue2 = 'value2';
//**failed to compile**
// var result = {{fieldName1:fieldValue1},{fieldName2,fieldValue2}};
var object1 = {};
object1[`${fieldName1}`] = fieldValue1;
var object2 = {};
object2[`${fieldName2}`] = fieldValue2;
var result = {object1, object2};
字段名称" name1"," name2"不是静态值。 预期结果是:
{
{ name1 : "value1" },
{ name2 : "value2" }
}
答案 0 :(得分:1)
使用此:
let object = {}
for(let field of allFields){
object[field] = value
}
此处allFields
是包含所有字段的数组。
答案 1 :(得分:0)
只需运行The Snippet,您就会明白:
var fieldName1 = 'name1';
var fieldValue1 = 'value1';
var fieldName2 = 'name2';
var fieldValue2 = 'value2';
var object = {};
object[fieldName1] = fieldValue1;
object[fieldName2] = fieldValue2;
console.log(object);
答案 2 :(得分:0)
如果要将值数组转换为JSON Object,请使用此选项。
var fieldName = ['name1','name2'];
var fieldValue =['value1','value2'];
var object = {};
for(i=0;i<fieldName.length;i++){
object[fieldName[i]]=fieldValue[i];
}
console.log(object);
答案 3 :(得分:0)
试试这个:
var fieldName1 = 'name1';
var fieldValue1 = 'value1';
var fieldName2 = 'name2';
var fieldValue2 = 'value2';
var object = {};
object[fieldName1] = fieldValue1;
object[fieldName2] = fieldValue2;
object = JSON.stringify(object);
object=object.replace(/"(\w+)"\s*:/g, '$1:');
console.log(object);
答案 4 :(得分:0)
观察:
解决方案:
var fieldName1 = 'name1';
var fieldValue1 = 'value1';
var fieldName2 = 'name2';
var fieldValue2 = 'value2';
var object1 = {};
var object2 = {};
object1[fieldName1] = fieldValue1;
object2[fieldName2] = fieldValue2;
console.log(new Array(object1, object2));
var fieldName1 = 'name1';
var fieldValue1 = 'value1';
var fieldName2 = 'name2';
var fieldValue2 = 'value2';
var jsonObject = {};
jsonObject[fieldName1] = fieldValue1;
jsonObject[fieldName2] = fieldValue2;
console.log(jsonObject);
答案 5 :(得分:0)
let object = {};
someRequest.forEach((value: string, key: string) => {
object[key]=value;
})