Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone an object omitting nested property

Tags:

javascript

I would like to make a copy of an existing object and omit some properties. Is there an easy es6+ way of removing the nested bar key for the following structure?

  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
  }
like image 684
ekjcfn3902039 Avatar asked Sep 16 '26 17:09

ekjcfn3902039


1 Answers

Make deep copy and remove unwanted fields

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);
like image 62
Kamil Kiełczewski Avatar answered Sep 19 '26 05:09

Kamil Kiełczewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!