0

I have this object:

728394 : {
    "playersAmount" : 2,
    "players" : {
      "LRFe9w9MQ6hf1urjAAAB" : {
        "nickname" : "spieler1",
        "type" : "player1"
      },
      "nKUDWEd5p_FCBO4sAAAD" : {
        "nickname" : "spieler2",
        "type" : "player2"
      },
      "ghdaWSWUdg27sf4sAAAC" : {
        "nickname" : "spieler3",
        "type" : "spectator"
      }
    },
    "activePlayer" : "LRFe9w9MQ6hf1urjAAAB",
    "board" : [
      [0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0]
    ]
  }

How do I get everything of the object above except for the k/v pair "board"? is there any other way than just adding every key except the right one?

4 Answers 4

3

You can create a copy and then delete the unwanted key:

const copy = { ...original }
delete copy.unwantedProperty

Of course you can instead delete the property on the original if you don't care about mutating it.

(Note: if your environment doesn't support the syntax { ...original }, you can use Object.assign({}, original) instead.)

EDIT: Actually, this answer is even neater.

Sign up to request clarification or add additional context in comments.

2 Comments

In case ES6 can't be used: var copy = JSON.parse(JSON.stringify(original)); delete copy.unwantedProperty;
That is much slower though and will destroy anything that cannot be represented with JSON, such as dates, functions, etc.
3
  const { board, ...everythingButBoard } = yourObject

1 Comment

Actually that's a really cool use of destructuring that I didn't think about! Neater than my answer.
1

simple answer will be:

const copyObject = Object.assign({}, yourObject) // to make a copy of original variable
delete copyObject['keyToRemove'] // OR delete copyObject.keyToRemove

else if you want to delete from original variable:

delete yourObject['keyToRemove'] // OR delete yourObject.keyToRemove

Comments

0

I think you can create a new object excluding this key using a for...in

object = {
  wantedKey: 'wantedValue',
  wantedKey2: 'wantedValue2',
  wantedKey3: 'wantedValue3',
  unwantedKey: 'unwantedValue'
}
const newObject = {}
for (const key in object) {
  if (key !== 'unwantedKey') newObject[key] = object[key]
}
console.log(newObject)

for more info about for...in: click here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.