1

I have an object that is converted using Object.keys() where the keys are stored in array. I am trying to loop through the array to splice out keys that are not needed for the rest of my function that I am trying to write.

var objectDef = { 
    pitcher: 'dave',
    runner: 'joel',
    umpire: 'kevin',
    action/0/id: 1,
    action/0/name: 'review', 
    action/0/killjoy: 'no' 
  }

  //define array of keys
 var givenObject = typeof objecDef == "object" ? Object.keys(objectDef) : [objectDef];

How would I go about splicing out splicing action/0/killjoy and action/0/name? I only want pitcher, runner, umpire, and action/0/id returned. These unwanted fields may or may not exist depending on the data that is received from the server.

Demon
  • 770
  • 6
  • 21
  • You could [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter?v=example) them out. – Mike Cluck May 15 '17 at 19:30
  • Your last line `typeof == "object"` should be throwing a syntax error... – Heretic Monkey May 15 '17 at 19:33
  • 1
    Possible duplicate of [How to remove a particular element from an array in JavaScript?](http://stackoverflow.com/questions/5767325/how-to-remove-a-particular-element-from-an-array-in-javascript) – Heretic Monkey May 15 '17 at 19:35
  • Sorry, it is a typo. Thanks for the correction. – Demon May 15 '17 at 19:39
  • 1
    It should be `typeof objectDef == "object"`. – Heretic Monkey May 15 '17 at 19:40
  • 1
    @Demon `typeOf == "object"` might have been correct if `typeOf` was defined, but _now_ it’s definitely wrong, because `typeof` is missing its operand. – Sebastian Simon May 15 '17 at 19:41
  • `action/0/name` is not a valid property name. –  May 15 '17 at 19:46
  • Okay. I corrected my error what I meant to say was use var givenObjects – Demon May 15 '17 at 19:47
  • Do you want to remove the unwanted property names from your array of property names, or to remove those properties and their values from the object? –  May 15 '17 at 19:59
  • I want to remove the unwanted property names in `givenObjects` because that is where I am trying to do other things with it. – Demon May 15 '17 at 20:14

2 Answers2

0
Object.keys(objectDef).filter(key=>typeof objectDef[key]!=="object");

Simply check if that objects element is an object...

Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120
  • well I'm trying to use array to store the all the keys and remove the last 2 elements from the arary so I can return the first 4 elements. – Demon May 15 '17 at 19:40
0

Use object spread/rest notation:

const {'action/0/killjoy': ignore1, 'action/0/name': ignore2, ...newObject} = objectDef;

newObject will now contain the remaining properties.

You'll need some kind of transpiler for this until there is browser support.