[英]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.