1

I am trying to figure out if I can send only relevant javascript info to the frontend from the backend because I want to hide things like ID, and others when my frontend makes a request.

To put things in perspective, here is a dummy code.

[
 {
  "_id": "215874514845452155",
  "greeting":"Hello there"
 },
 {
  "_id": "181474545841541515",
  "greeting": "General Kenobi"
 },
]

when requesting, I want to get result like:

[
 {
  "greeting": "Hello there"
 },
 {
  "greeting": "General Kenobi"
 },
]

I am still learning stuff and I know about loop function but I want to know if there is some neat trick to it. I am coming from R programming, we hate loops.

1 Answers1

0

Use Array.prototype.map:

const input = [
 {
  "_id": "215874514845452155",
  "greeting":"Hello there",
  "other":"foo"
 },
 {
  "_id": "181474545841541515",
  "greeting": "General Kenobi",
  "other":"bar"
 },
];

const result = input.map(({greeting,other}) => ({greeting,other}));
console.log(result);

The above is a shorthand way of writing this:

const input = [
 {
  "_id": "215874514845452155",
  "greeting":"Hello there",
  "other":"foo"
 },
 {
  "_id": "181474545841541515",
  "greeting": "General Kenobi",
  "other":"bar"
 },
];

const result = input.map(x => {
  return {
    greeting: x.greeting,
    other: x.other
  }
});
console.log(result);
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • @ashishbajaj it might be hard to understand what thats doing if you're not used to destructuring/object creation. check the update – Jamiec Feb 05 '21 at 10:32
  • Yes, I get it. The new update also works but I think I will go with destructuring. Looks neat. – ashish bajaj Feb 05 '21 at 10:37
  • @ashishbajaj the second one has a lot of repetition, which is why the destructing route is nicer – Jamiec Feb 05 '21 at 10:38