Lokomotywa
Lokomotywa

Reputation: 2844

Getting only non-prototype properties of object

Is there a way to create an copy of an JS Object that contains only the non-prototype properties of the Object?

Like this:

 var copy = object.onlyOwnProperties();

Upvotes: 2

Views: 806

Answers (1)

Mark
Mark

Reputation: 92440

Objects, as you probably know, are prototype linked — so they don't really have prototype properties. They are linked to another object that has properties and the system looks up the chain when it can't find a property. So you can't remove something the object doesn't have.

You can however break the chain and make an object that isn't linked to anything with Object.create(null). For example:

let o = {
  name: "Mark",
  trade: "Pirate"
}
// o is linked to the Object prototype and
// gets these props from the Object
console.log(Object.getOwnPropertyNames(o.__proto__))

// which means it has things like toString()
console.log(o.toString())

// bare is a stand alone with no prototype
// it will ONLY have the two props
let bare = Object.assign(Object.create(null), o)
console.log(bare.__proto__)

// no toString or anything else
console.log(bare.toString)

// just original props
console.log(bare.name)

Maybe that's too extreme and you really want the object methods, but nothing else. In that case you can Object.assign with an Object literal:

let o = {
  name: "Mark",
  trade: "Pirate"
}

let child = {
  childProp: "someVal"
}


Object.setPrototypeOf(child, o)

// child gets o props through prototype
console.log("from prototype:", child.name)

// make an object with only child props
// that is still linked to the Object prototype
let bareChild = Object.assign({}, child)

// no props from o
console.log("from prototype:", bareChild.name)

// just it's own
console.log("own prop:", bareChild.childProp)

// but this still works:
console.log("toString", bareChild.toString())

Upvotes: 3

Related Questions