通过键从对象内部的所有对象中删除元素

时间:2019-05-10 16:05:33

标签: javascript

我有这个对象:

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",
        }]
    }
}

4 个答案:

答案 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)

jsfiddle

答案 3 :(得分:1)

您可以使用for...in循环遍历test的键。然后使用for...ofdeletepath中的每个对象中删除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)