我有一个包含多个嵌套数组和映射的复杂javascript对象。我想删除具有给定名称的对象的每个字段。
例如:
{ "myObj":{ "name":"John", "deleteMe":30, "cars":{ "car1":"Ford", "car2":"BMW", "deleteMe":"Fiat", "wheels":{ "one":"Round", "two":"Square", "deleteMe":"Fiat" } } }}
如何删除名称/键为“ deleteMe”的每个字段。我不知道对象的结构。
const myObj ={ "name":"John", "deleteMe":30, "cars":{ "car1":"Ford", "car2":"BMW", "deleteMe":"Fiat", "wheels":{ "one":"Round", "two":"Square", "deleteMe":"Fiat" } }}const recursiveRemoveKey = (object, deleteKey) => { delete object[deleteKey]; Object.values(object).forEach((val) => { if (typeof val !== 'object') return; recursiveRemoveKey(val, deleteKey); })}recursiveRemoveKey(myObj, 'deleteMe');console.log(myObj);
您需要在对象中找到键,或者递归地归入本身就是对象的任何值:
function deleteMe(obj, match) { delete obj[match]; for (let v of Object.values(obj)) { if (v instanceof Object) { deleteMe(v, match); } }}
这样的事情应该工作:
const obj = { "myObj":{ "name":"John", "deleteMe":30, "cars":{ "car1":"Ford", "car2":"BMW", "deleteMe":"Fiat", "wheels":{ "one":"Round", "two":"Square", "deleteMe":"Fiat" } } } } const deleteField = (obj, field) => { Object.keys(obj).forEach((key) => { if (key === field) { delete obj[key]; } else if (typeof obj[key] === "object") { deleteField(obj[key], field); } }) } deleteField(obj, "deleteMe"); console.log(obj);
您可以递归遍历每个嵌套对象,并在每个级别上删除所需的任何键。
请注意,这将修改现有对象。
const main = () => { console.log(pruneKeys(getData(), 'deleteMe')) } /** Wrapper */ const pruneKeys = (obj, ...keys) => { __pruneKeysInner(obj, new Set(keys.length && Array.isArray(keys[0]) ? keys[0] : keys)) return obj } /** Recursive call */ const __pruneKeysInner = (obj, keySet) => { if (obj != null && isObject(obj)) { for (key in obj) { if (keySet.has(key)) { delete obj[key] } else { __pruneKeysInner(obj[key], keySet) } } } } const isObject = n => Object.prototype.toString.call(n) === '[object Object]' const getData = () => ({ "myObj": { "name": "John", "deleteMe": 30, "cars": { "car1": "Ford", "car2": "BMW", "deleteMe": "Fiat", "wheels": { "one": "Round", "two": "Square", "deleteMe": "Fiat" } } } }) main()
.as-console-wrapper { top: 0; max-height: 100% !important; }