我有这个对象:
const test = {
"/test2": {
"path": "/test",
"items": [{
"path": "/test",
"method": "GET",
}, {
"path": "/test",
"method": "PUT",
}]
},
"/test": {
"path": "/test2",
"items": [{
"path": "/test2",
"method": "GET",
}]
}
}
我想删除每个对象内部的嵌套元素path
,以便最终得到这样的东西:
const test = {
"/test": {
"path": "/test",
"items": [{
"method": "GET",
}, {
"method": "PUT",
}]
},
"/test2": {
"path": "/test2",
"items": [{
"method": "GET",
}]
}
}
答案 0 :(得分:2)
您可以通过删除不需要的属性并对对象的所有嵌套值进行迭代来采用递归和迭代的方法。
function delKey(key) {
return function d(object) {
if (!object || typeof object !== 'object') return;
delete object[key];
Object.values(object).forEach(d);
};
}
const test = { "/test": { path: "/test", items: [{ path: "/test", method: "GET" }, { path: "/test", method: "PUT" }] }, "/test2": { path: "/test2", items: [{ path: "/test2", method: "GET", }] } };
delKey('path')(test);
console.log(test);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
您可以使用Object.entries
将对象转换为数组。使用reduce
遍历数组。使用map
遍历items
并仅返回method
const test = {"/test2":{"path":"/test","items":[{"path":"/test","method":"GET"},{"path":"/test","method":"PUT"}]},"/test":{"path":"/test2","items":[{"path":"/test2","method":"GET"}]}};
const result = Object.entries(test).reduce((c, [k, {path,items}]) => {
c[k] = {path};
c[k].items = items.map(({method}) => ({method}));
return c;
}, {});
console.log(result);
答案 2 :(得分:1)
您可以使用以下内容:
const data = {
"/test2": {
"path": "/test",
"items": [{
"path": "/test",
"method": "GET",
}, {
"path": "/test",
"method": "PUT",
}]
},
"/test": {
"path": "/test2",
"items": [{
"path": "/test2",
"method": "GET",
}]
}
}
Object.keys(data).forEach(k => {
data[k].items.forEach(item => {
delete item['path']
})
})
console.log(data)
答案 3 :(得分:1)
您可以使用for...in
循环遍历test
的键。然后使用for...of
和delete
从path
中的每个对象中删除items
:
const test = { "/test": { path: "/test", items: [{ path: "/test", method: "GET" }, { path: "/test", method: "PUT" }] }, "/test2": { path: "/test2", items: [{ path: "/test2", method: "GET", }] } };
for (let key in test) {
for (let item of test[key].items) {
delete item.path
}
}
console.log(test)