-1

I have a javascript object like this:

let obj = {
    foo: "bar",
    baz: "quux",
    banana: "apple"
}

And i want another object containing all the properties in obj but one, something like

{
    foo: "bar",
    banana: "apple"
}

I don't want to change obj, so using delete is not an option, and i'd also like to avoid writing a function that loops on Object.keys and sets all properties but baz to a new object.

Is there a native function to do something like this, basically like a slice for objects?

Raibaz
  • 9,280
  • 10
  • 44
  • 65
  • You could use [*Object.assign*](http://ecma-international.org/ecma-262/7.0/index.html#sec-object.assign) to "copy" the object, then delete the unwanted property. – RobG May 12 '17 at 08:58
  • var clone = Object.assign({}, obj); delete clone.baz; – JYoThI May 12 '17 at 08:59

1 Answers1

1

Assign to new object and delete unwanted

let obj = {
    foo: "bar",
    baz: "quux",
    banana: "apple"
};

var clone = Object.assign({},obj);
delete clone.baz;

console.log(clone);
JYoThI
  • 11,977
  • 1
  • 11
  • 26
  • `delete` can be slow. [jsperf](https://jsperf.com/delete-vs-undefined-vs-null/16). Use it when you doesn't care about perf and you know what are you doing. [see](http://stackoverflow.com/a/21735614/1248177) – aloisdg May 12 '17 at 09:05
  • thanks for the info @aloisdg – JYoThI May 12 '17 at 09:07
  • @aloisdg: Of course a re-assignment is going to be faster. `delete` also is the only method to properly ___remove___ a property from an object. – Cerbrus May 12 '17 at 09:07
  • Also, that benchmark is [horribly outdated](http://jsben.ch/#/gu1Gi), @aloisdg. – Cerbrus May 12 '17 at 09:12