克隆一个忽略嵌套属性的对象

时间:2019-08-20 19:39:51

标签: javascript

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

  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
  }

4 个答案:

答案 0 :(得分:4)

进行深度复制并删除不需要的字段

let clone = JSON.parse(JSON.stringify(someObj)); 
clone.someList.forEach(x=> delete x.bar);

let someObj = { 
    someList: [
      { foo:'1', bar:'x',  },
      { foo:'2', bar:'x',  },
      { foo:'3', bar:'x',  },
    ],
    otherPropOne: '',
    anotherProp: [],
    //etc
  }
  
let clone = JSON.parse(JSON.stringify(someObj)); 
clone.someList.forEach(x=> delete x.bar);

console.log(clone);

答案 1 :(得分:3)

您可以复制对象,然后删除副本中不需要的变量。看到这个副本 https://repl.it/repls/NarrowWearyConstant

let 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
}

let clone = JSON.parse(JSON.stringify(someObj));
clone.someList = copy.someList.map((val, i) => {
  delete val.bar;
  // delete val.otherField
  return val;
})
console.log(someObj, clone);

答案 2 :(得分:2)

复制对象有两种方法

ES6方式

您可以使用传播算子(...)轻松复制该对象

    const mainObj = { id: 1 };
    const newObj = { ...mainObj };

但这是一个浅表副本,因此,如果您在newObj中进行任何更改,它也会在mainObj中复制。

  const mainObj = {
    someList: [
      { foo: '1', bar: 'x' },
      { foo: '2', bar: 'x' },
      { foo: '3', bar: 'x' }
    ],
    otherPropOne: '',
    anotherProp: []
  };
  
  const newObj = { ...mainObj };
  newObj.someList.forEach((f) => { delete f.bar; });
  console.log(mainObj, newObj);

原生方式

    const mainObj = { id: 1 };
    const newObj = JSON.parse(JSON.stringify(mainObj));
  

好处newObj中的更改不会影响mainObj

  const mainObj = {
    someList: [
      { foo: '1', bar: 'x' },
      { foo: '2', bar: 'x' },
      { foo: '3', bar: 'x' }
    ],
    otherPropOne: '',
    anotherProp: []
  };

  const newObj = JSON.parse(JSON.stringify(mainObj));
  newObj.someList.forEach((f) => { delete f.bar; });
  console.log(mainObj, newObj);

答案 3 :(得分:1)

首先,您需要克隆对象,不幸的是,在es6中没有简单的方法来实现此目的。
除非您具有循环依赖性,否则简单的JSON.stringifyJSON.parse应该可以解决问题。

let copy = JSON.parse(JSON.stringify(someObj));

要删除bar道具,可以对.map使用解构:

copy.someList = copy.someList.map(({bar, ...otherProps}) => otherProps);

完整示例:

let someObj = {
  someList: [{
      foo: '1',
      bar: 'x',
    },
    {
      foo: '2',
      bar: 'x',
    },
    {
      foo: '3',
      bar: 'x',
    },
  ],
  otherPropOne: '',
  anotherProp: [],
  //etc
};

let clone = JSON.parse(JSON.stringify(someObj));
clone.someList = clone.someList.map(({bar, ...otherProps}) => otherProps);
console.log(clone);