How to omit specific properties from an object in JavaScript

后端 未结 14 1290
无人共我
无人共我 2021-02-01 14:50

Is there a clean way to return a new object that omits certain properties that the original object contains without having to use something like lodash?

14条回答
  •  时光取名叫无心
    2021-02-01 15:27

    You can use Object.assign(), delete

    var not = ["a", "b"]; // properties to delete from obj object
    var o = Object.assign({}, obj);
    for (let n of not) delete o[n];
    

    Alternatively

    var props = ["c", "d"];
    let o = Object.assign({}, ...props.map(prop => ({[prop]:obj[prop]})));
    

提交回复
热议问题