我有一个 Angular 2 表单值,它是在表单(表单值(提交后通过以下方式生成的,
表单数据:
{
"LoyaltyNumber": "mal",
"CardAcceptorName": "John",
}
我还有另一个 JSON 对象,我们需要将最终值发送到服务器。
{
"LoyaltyNumber": {
"tcId": "PREQ_001",
"msgSeq": 1,
"value": ""
},
"CardAcceptorName": {
"tcId": "PREQ_001",
"msgSeq": 1,
"value": ""
}
}
而且,我想使用第一个 JSON 中的值从第二个 JSON 更新value
。
您可以使用Object.keys()
来迭代第一个 json 对象的键。Object.keys()
返回一个包含键名的字符串数组。因此,我们可以就该结果致电.forEach()
。在foreach方法中,我们可以使用键来访问secondJsonObj
中的子对象。
Object.keys(firstJsonObj).forEach(key => {
if (secondJsonObj[key]) {
secondJsonObj[key].value = firstJsonObj[key]
}
});
第一个JSON分配给firstJsonObj,第二个JSON分配给secondJsonObj;
firstJsonObj = {
"LoyaltyNumber": "mal",
"CardAcceptorName": "John",
};
secondJsonObj = {
"LoyaltyNumber": {
"tcId": "PREQ_001",
"msgSeq": 1,
"value": ""
},
"CardAcceptorName": {
"tcId": "PREQ_001",
"msgSeq": 1,
"value": ""
}
};
您可以像这样分配值
secondJsonObj.LoyaltyNumber.value = firstJsonObj.LoyaltyNumber;
secondJsonObj.CardAcceptorName.value = firstJsonObj.CardAcceptorName;
如果你想要动态。
Object.keys(firstJsonObj).forEach(function(key){
secondJsonObj[key]. value = firstJsonObj[key];
});
试试这个:
var json1 = {
"LoyaltyNumber": "mal",
"CardAcceptorName": "John"
};
var json2 = {
"LoyaltyNumber": {
"tcId": "PREQ_001",
"msgSeq": 1,
"value": ""
},
"CardAcceptorName": {
"tcId": "PREQ_001",
"msgSeq": 1,
"value": ""
}
};
json2.LoyaltyNumber.value = json1.LoyaltyNumber;
json2.CardAcceptorName.value= json1.CardAcceptorName;
console.log(JSON.stringify(json2));
输出:
{"LoyaltyNumber":{"tcId":"PREQ_001","msgSeq":1,"value":"mal"},">CardAcceptorName":{"tcId":"PREQ_001","msgSeq":1,"value":"John"}}