4

My json object looks like this

Object
  A:Object
  B:Object
  C:Object
  D Object
  E:Object
  F:Object
  __proto__:Object

I want to get only D and E from this json object based on key. New json object should only include D and E. how to acheive this?

Loura
  • 109
  • 5
  • 18
  • This question about filtering a single JSON abject however in duplicate tag question is about JSON array. Need to remove duplicate – Prasad Parab Apr 10 '21 at 16:22

4 Answers4

2

Try this:

function copyObjectProps(source, keys) {
   let newObject = {}
   keys.forEach(function(key) {
     newObject[key] = source[key]
   })
   return newObject
}

And use it like:

let filteredObject = copyObjectProps(yourObject, ['D', 'E'])
Maher Fattouh
  • 1,742
  • 16
  • 24
Amresh Venugopal
  • 9,299
  • 5
  • 38
  • 52
0

Object['D'] and Object['E'] will give you direct access to corresponding objects.

You can create new object using..

var newObj = { D : Object['D'], E : Object['E']}

Use original object name instead of Object for accessing.

Using JSON.stringify(newObj); to can get the new JSON.

Atul Sharma
  • 9,397
  • 10
  • 38
  • 65
0

Filter only applies to arrays. Therefore, you need to define a new variable and run a for loop.

var mynewobject ={};
for (var key in myobject)
{
   if (...) // apply your condition here
      mynewobject[key] = myobject[key]
}
Amir H. Bagheri
  • 1,416
  • 1
  • 9
  • 17
0

Use underscrore(http://underscorejs.org/) or loadash(https://lodash.com/).

The have methods like _.pick to pick specific nodes.

many more options are also available.

Srisudhir T
  • 685
  • 10
  • 24