2

I'm trying to select certain keys from an JSON array, and filter the rest.

var json = JSON.stringify(body);

which is:

{  
   "FirstName":"foo",
   "typeform_form_submits":{  
      "foo":true,
      "bar":true,
      "baz":true
   },
  "more keys": "foo",
  "unwanted key": "foo"
}

Want I want:

{  
   "FirstName":"foo",
   "typeform_form_submits":{  
      "foo":true,
      "bar":true,
      "baz":true
   }
}

I've checked out How to filter JSON data in node.js?, but I'm looking to do this without any packages.

1

4 Answers 4

5

Now you can use Object.fromEntries like so:

Object.fromEntries(Object.entries(raw).filter(([key]) => wantedKeys.includes(key)))
Sign up to request clarification or add additional context in comments.

Comments

2

You need to filter your obj before passing it to json stringify:

const rawJson = {  
   "FirstName":"foo",
   "typeform_form_submits":{  
      "foo":true,
      "bar":true,
      "baz":true
   },
  "more keys": "foo",
  "unwanted key": "foo"
};

// This array will serve as a whitelist to select keys you want to keep in rawJson
const filterArray = [
  "FirstName",
  "typeform_form_submits",
];

// this function filters source keys (one level deep) according to whitelist
function filterObj(source, whiteList) {
  const res = {};
  // iterate over each keys of source
  Object.keys(source).forEach((key) => {
    // if whiteList contains the current key, add this key to res
    if (whiteList.indexOf(key) !== -1) {
      res[key] = source[key];
    }
  });
  return res;
}

// outputs the desired result
console.log(JSON.stringify(filterObj(rawJson, filterArray)));

3 Comments

I'm getting the error "filterObj is not defined", yet your snippet is working great. Any ideas?
Nevermind, got the answer below to work- I'm not sure what made the difference!
Worked like a charm and I could expand it out to have arrays of key value pairs
1

var raw = {  
   "FirstName":"foo",
   "typeform_form_submits":{  
      "foo":true,
      "bar":true,
      "baz":true
   },
  "more keys": "foo",
  "unwanted key": "foo"
}
var wantedKeys =["FirstName","typeform_form_submits" ]
var opObj = {}
Object.keys(raw).forEach( key => {
   if(wantedKeys.includes(key)){
    opObj[key] = raw[key]
 }
})

console.log(JSON.stringify(opObj))

Comments

0

I know this question was asked aways back, but I wanted to just toss out there, since nobody else did:

If you're bound and determined to do this with stringify, one of its less-well-known capabilities involves replacer, it's second parameter. For example:

// Creating a demo data set
let dataToReduce = {a:1, b:2, c:3, d:4, e:5};
console.log('Demo data:', dataToReduce);

// Providing an array to reduce the results down to only those specified.
let reducedData = JSON.stringify(dataToReduce, ['a','c','e']);
console.log('Using [reducer] as an array of IDs:', reducedData);

// Running a function against the key/value pairs to reduce the results down to those desired.
let processedData = JSON.stringify(dataToReduce, (key, value) => (value%2 === 0) ? undefined: value);
console.log('Using [reducer] as an operation on the values:', processedData);

// And, of course, restoring them back to their original object format:
console.log('Restoration of the results:', '\nreducedData:', JSON.parse(reducedData), '\nprocessedData:', JSON.parse(processedData));

In the above code snippet, the key value pairs are filtered using stringify exclusively:

  • In the first case, by providing an array of strings, representing the keys you wish to preserve (as you were requesting)
  • In the second, by running a function against the values, and dynamically determining those to keep (which you didn't request, but is part of the same property, and may help someone else)
  • In the third, their respective conversions back to JSON (using .parse()).

Now, I want to stress that I'm not advocating this as the appropriate method to reduce an object (though it will make a clean SHALLOW copy of said object, and is actually surprisingly performant), if only from an obscurity/readability standpoint, but it IS a totally-effective (and mainstream; that is: it's built into the language, not a hack) option/tool to add to the arsenal.

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.