2

I have an Object array named users. The object format in this array looks like this:

var userExample = {pub:{name:'John', id:'100'}, priv:{location:'NYC', phone:'000000'}};

As a restful service, clients may request information of all users. And obviously I just want to send public information to them. So I want to serialize my data selectively by keys(priv key will be ignored)

Here is my code snippet:

var users = [];
function censor(key, value) {
  if (key == priv) {
    return undefined;
  }
  return value;
}

app.get('/listUsers', function(req, res){
  res.end(JSON.stringify(users, censor));
});

When I run these code, an error occurred:

ReferenceError: priv is not defined

I'm a Javascript beginner, please help.

0

3 Answers 3

1

Change priv to "priv".

But your approach is dangerous. In similar conditions I usually create a new object to export and I explicitly copy the properties which should be exported, this way there's no risk of leak on future data structure changes. A white list is always more future proof than a black list.

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

1 Comment

Thanks, you're correct. And thanks again for your advice, I'll try that way.
0

Newer versions of JSON.stringify() have a replacer array

E.g.

```
JSON.stringify(foo, ['week', 'month']);  
// '{"week":45,"month":7}', only keep "week" and "month" properties
```

Comments

0

Try with:

 if (key == "priv")

This should work.

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.