[英]How to replacing properties of an json object with new
此 object 生成取決於來自后端的自定義字段。 需要一個 function 來替換新的和其他刪除的某些字段或不包括在提交 object
{
"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 中的屬性值,但不幸的是。 如果你幫助我,我將不勝感激
如果您想要的更改非常具體,您知道要更改的每個字段,您可以修改每個屬性。 如果上面的 object 在變量 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 的所有屬性,請使用 Object.values
Object.values(x).forEach((key,val)=>console.log(key,val))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.