使用动态字段名在Angular中构造json对象

zlwx9yxi  于 2023-03-20  发布在  Angular
关注(0)|答案(7)|浏览(174)

新手问题:有没有更好的方法在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" }
}
voase2hg

voase2hg1#

只要运行代码段,你会得到的想法:

var fieldName1 = 'name1';
var fieldValue1 = 'value1';
var fieldName2 = 'name2';
var fieldValue2 = 'value2';

var object = {};
object[fieldName1] = fieldValue1;
object[fieldName2] = fieldValue2;

console.log(object);
nfs0ujit

nfs0ujit2#

使用此命令:

let object = {}
for(let field of allFields){
    object[field] = value
}

这里allFields是一个包含所有字段的数组。

xj3cbfub

xj3cbfub3#

如果你想把数组的值转换成JSON对象,可以使用这个方法。

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);
mklgxw1f

mklgxw1f4#

试试这个:

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);
7qhs6swi

7qhs6swi5#

意见:

  • OP中的expected result没有有效的JSON。

解决方案:
*对象数组:

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);
nkcskrwz

nkcskrwz6#

let object = {};
someRequest.forEach((value: string, key: string) => {
    object[key]=value;
})
wlwcrazw

wlwcrazw7#

对于Angular 11或更大,需要声明类型,例如:

type tplotOptions = {
    [key: string]: boolean
}
const plotOptions: tplotOptions = {
    train_1: true,
    train_2: true
}

type tplotOptions = {
    [key: string]: string
}
const plotOptions: tplotOptions = {
    train_1: 'data1',
    train_2: 'data2'
}

相关问题