[英]Copy an object into another based on condition
假設我有這個示例 object,如下所示,
let parentObj = {
"SM": {
"child_roles": {
"SM#02": {
"code": "SM#02",
"assigned_info": [
{
"cur_assigned_to": "7486",
"assigned_date": 1644483524,
"assigned_fromdate": 1644517800,
"assigned_todate": 1645122600,
},
{
"cur_assigned_to": "3050",
"assigned_date": 1656613800,
"assigned_fromdate": 1658255400,
"assigned_todate": 1659292200,
}
]
},
"SM#03": {
"code": "SM#03",
"assigned_info": [
{
"cur_assigned_to": "7486",
"assigned_date": 1644483638,
"assigned_fromdate": 1644517800,
"assigned_todate": 1645727400,
},
{
"cur_assigned_to": "3050",
"assigned_date": 1656613800,
"assigned_fromdate": 1656613800,
"assigned_todate": 1660069800,
}
]
},
"SM#01": {
"code": "SM#01",
"assigned_info": []
}
}
},
"SMP": {
"child_roles": {
"SMP#01": {
"code": "SMPR#01",
"assigned_info": [
{
"cur_assigned_to": "7486",
"assigned_date": 1644483672,
"assigned_fromdate": 1644431400,
"assigned_todate": 1645122600,
}
]
}
}
},
"SMR": {
"child_roles": {
"SMR#01": {
"code": "SMOR#01",
"assigned_info": []
},
"SMOR#02": {
"code": "SMOR#02",
"assigned_info": []
}
}
},
"ANC": {
"child_roles": {}
}
}
現在有一個名為assigned_info的鍵,這是一個賦值信息的集合。 我想檢查它是否包含 cur_assigned_to = 3050 的項目,然后復制該數組項目以及該 object 的其他屬性。 對不起我的英語不好,換句話說,我想得到這個 output 如下所示,
let expectedObj = {
"SM": {
"child_roles": {
"SM#02": {
"code": "SM#02",
"assigned_info": [
{
"cur_assigned_to": "3050",
"assigned_date": 1656613800,
"assigned_fromdate": 1658255400,
"assigned_todate": 1659292200,
}
]
},
"SM#03": {
"code": "SM#03",
"assigned_info": [
{
"cur_assigned_to": "3050",
"assigned_date": 1656613800,
"assigned_fromdate": 1656613800,
"assigned_todate": 1660069800,
}
]
},
"SM#01": {
"code": "SM#01",
"assigned_info": []
}
}
},
"SMP": {
"child_roles": {
"SMP#01": {
"code": "SMPR#01",
"assigned_info": [
]
}
}
},
"SMR": {
"child_roles": {
"SMR#01": {
"code": "SMOR#01",
"assigned_info": []
},
"SMOR#02": {
"code": "SMOR#02",
"assigned_info": []
}
}
},
"ANC": {
"child_roles": {}
}
}
我已經嘗試過:我可以遍歷該assigned_info 數組的所有元素並檢查cur_assigned_to 是否為3050,但我無法復制剩余的鍵並且無法刪除其他數組元素。
您可以復制整個parentObj
並刪除數組中的意外項目。
let objCopy = JSON.parse(JSON.stringify(parentObj))
for (let i in objCopy) {
for (let j in objCopy[i]['child_roles']) {
let obj = objCopy[i]['child_roles'][j]['assigned_info']
for (let k in obj) {
if ('cur_assigned_to' in obj[k] && obj[k].cur_assigned_to != '3050') {
obj.splice(k, 1)
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.