Javascript 克隆忽略嵌套属性的对象

Javascript 克隆忽略嵌套属性的对象,javascript,Javascript,我想复制一个现有对象并省略一些属性。是否有一种简单的es6+方法可以移除以下结构的嵌套条键 someObj = { someList: [ { foo:'1', bar:'x', /*etc could be more values*/ }, { foo:'2', bar:'x', /*etc could be more values*/ }, { foo:'3', bar:'x', /*etc could be more values*/ },

我想复制一个现有对象并省略一些属性。是否有一种简单的es6+方法可以移除以下结构的嵌套条键

  someObj = { 
    someList: [
      { foo:'1', bar:'x', /*etc could be more values*/ },
      { foo:'2', bar:'x', /*etc could be more values*/ },
      { foo:'3', bar:'x', /*etc could be more values*/ },
    ],
    otherPropOne: '',
    anotherProp: [],
    //etc
  }

对象的副本有两种方法

ES6方式

您可以使用扩展运算符(
)轻松复制该对象

但是它是一个浅拷贝,所以如果您在
newObj
中进行任何更改,它也会在
mainObj
中复制

const mainObj={
人物列表:[
{foo:'1',bar:'x'},
{foo'2',bar'x'},
{foo:'3',bar:'x'}
],
其他人:'',
另一个项目:[]
};
const newObj={…mainObj};
forEach((f)=>{delete f.bar;});

控制台日志(mainObj、newObj)您可以复制对象,然后删除副本中不需要的变量。看到这个回复了吗


首先,您需要克隆对象,不幸的是,在es6中没有简单的方法可以做到这一点。
一个简单的
JSON.stringify
JSON.parse
应该可以做到这一点,除非您有循环依赖关系

let copy = JSON.parse(JSON.stringify(someObj));
要删除
道具,可以使用
.map
进行分解:

copy.someList = copy.someList.map(({bar, ...otherProps}) => otherProps);
完整示例:

让someObj={
人物列表:[{
傅:"1",,
酒吧:“x”,
},
{
傅:"2",,
酒吧:“x”,
},
{
傅:"3",,
酒吧:“x”,
},
],
其他人:'',
另一个项目:[],
//等
};
让clone=JSON.parse(JSON.stringify(someObj));
clone.someList=clone.someList.map(({bar,…otherProps})=>otherProps);

console.log(克隆)进行深度复制并删除不需要的字段

let clone = JSON.parse(JSON.stringify(someObj)); 
clone.someList.forEach(x=> delete x.bar);
让someObj={
人物列表:[
{foo:'1',bar:'x',},
{foo:'2',bar:'x',},
{foo:'3',bar:'x',},
],
其他人:'',
另一个项目:[],
//等
}
让clone=JSON.parse(JSON.stringify(someObj));
clone.someList.forEach(x=>delete x.bar);

console.log(克隆)对于上述示例中的嵌套结构,这是如何工作的?spread操作符执行浅层复制。我认为这会忽略嵌套对象,但事实并非如此,包含对象的键仍然会在这两个对象上发生变异objects@AsafAviv完全同意你的意见,我更新了我的答案可能是
copy.someList = copy.someList.map(({bar, ...otherProps}) => otherProps);
let clone = JSON.parse(JSON.stringify(someObj)); 
clone.someList.forEach(x=> delete x.bar);