如何用new替换json对象的属性



此对象生成依赖于来自后端的自定义字段。需要一个函数来替换新的和其他删除或不包括在提交对象中的一些字段

{
"originating_office": {
"code": "string", **replace on "value": "string",**
"description": "string" **replace on "label": "string"**
},
"petty_cash_account": {
"number": "string", **replace on "value": "string",**
"name": "SOME DATA", **replace on "value": "string",**
"gls_account": "SOME DATA-HERE", **just add new filed**
"currency": "SOME", **just add new filed**
"origination_office_of": "" **just add new filed**
},
"item": "simple string",
"amount": "0.7",
"spending_unit": {
"indexno": "08805544", **save**
"display_name": "Mark Twen", **delete**
"position_title": null, **delete**
"org_unit_name": "", **delete**
"extension": null, **delete**
"country": "Italy", **delete**
"duty_station": "2250", **delete**
"email": "user@example.com", **save**
"last_name": "Some", **save**
"first_name": "Data", **save**
"username": "some.data", **delete**
"text": "Some DATA" **save**
},
}

但无法想象向前该怎么办

const replaceDataByNew = (obj) => {
for (let i = 0; i < obj.length; i++) {
if (obj[i].hasOwnProperty('originating_office')) {
console.log("originating_office");

}
if (obj[i].hasOwnProperty('cash_collected')) {
console.log("cash_collected");
}
}
};
replaceDataByNew(data);

我尝试重构下一种方法:替换JSON中的属性值,但不幸的是。如果你帮我,我将不胜感激

如果您想要的更改非常具体,您知道要更改的每个字段,则可以修改每个属性。如果上面的对象在变量x 中

let x = {
originating_office: { code: "string", description: "string" },
petty_cash_account: {
number: "string",
and so on

你可以简单地这样做。

//This modifies the value of code to "A new string"
x.originating_office.code = "A new string";    
//This deletes the display_name property on the spending unit property
delete x.spending_unit.display_name;
//You can also reference properties using this format
delete x["spending_unit"]["display_name"];
//Javascript is dynamic, you add a new property like this.
x.petty_cash_account.currency = "USD";

如果您想循环遍历对象的所有属性,请使用object.values

Object.values(x).forEach((key,val)=>console.log(key,val))

最新更新