Если вы хотите изменить исходный список в строке, вы можете рекурсивно удалить ключи, используя ссылку на объект следующим образом:
{
"drugName" : true,
"mailPrice" : {
"copayEmployer" : true
},
"retialPrice" : {
"copayEmployer" : true
}
}
Пример
Примечание: У вас есть опечатка в вашем первом объекте, т.е. "retialPrice"
вместо "retailPrice"
.Вот почему поле "copayEmployer"
не игнорируется в копии.
const data = getData()
const ignore = {
"drugName": true,
"mailPrice": {
"copayEmployer": true
},
"retailPrice": {
"copayEmployer": true
}
}
console.log('Original:', data)
console.log('Cloned:', cloneAll(data, ignore)) // Does not alter data
console.log('Unmodified:', data)
console.log('Pruned:', pruneAll(data, ignore)) // Alters the data
console.log('Modified:', data)
// Main call to pass in the list to copy items
function cloneAll(data, ignoreObj) {
return data.map(item => clone(item, ignoreObj))
}
// Clones an object and ignores properties
function clone(obj, ignoreObj) {
if (obj === null || typeof(obj) !== 'object' || 'isActiveClone' in obj) {
return obj
}
let temp = obj.constructor()
for (let key in obj) {
if (ignoreObj == null || ignoreObj[key] !== true) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
obj['isActiveClone'] = null
temp[key] = clone(obj[key], ignoreObj != null ? ignoreObj[key] : null)
delete obj['isActiveClone']
}
}
}
return temp
}
// Main call to pass in the list to prune
function pruneAll(data, ignoreObj) {
return data.map(item => prune(item, ignoreObj))
}
// Recursive helper method to work on each item
function prune(obj, ignoreObj) {
if (obj != null && ignoreObj != null) {
Object.keys(ignoreObj).forEach(key => {
if (ignoreObj[key] === true) {
delete obj[key] // Prune property-value
} else {
prune(obj[key], ignoreObj[key])
}
})
}
return obj
}
function getData() {
return [{
"isBrand": true,
"drugName": "Lipitor",
"drugStrength": "80 mg",
"drugForm": "Tablet",
"mailPrice": {
"copayEmployer": 0,
"prop2": "test"
},
"retialPrice": {
"copayEmployer": 0,
"prop2": "test"
}
}, {
"isBrand": true,
"drugName": "Metformin",
"drugStrength": "500 mg",
"drugForm": "Tablet",
"mailPrice": {
"copayEmployer": 50,
"prop2": "test"
},
"retailPrice": {
"copayEmployer": 0,
"prop2": "test"
}
}]
}
.as-console-wrapper {
top: 0;
max-height: 100% !important;
}