0

I have a nodejs Get request which returns the following array:

const array = [{
  name: 'Alex',
  age: 10,
  details: [{
    day: 'Monday',
    asst: 'Leo',
    subDetails: [{ color: 'green', qty: 85 }, { color: 'orange', qty: 35 }]
  },
  {
    day: 'Tuesday',
    asst: 'Shaun',
    subDetails: [{ color: 'brown', qty: 15 }, { color: 'indigo', qty: 35 }]
  },
  {
    day: 'Wednesday',
    asst: 'Julian',
    subDetails: [{ color: 'pink', qty: 25 }, { color: 'blue', qty: 15 }]
  },
  {
    day: 'Thursday',
    asst: 'Luis',
    subDetails: [{ color: 'peach', qty: 5 }, { color: 'black', qty: 15 }]
  },
  ]
}]

I want to further filter the result from the nodejs before it will be sent to the frontend. I want to get the array and nested array on Monday. Here is my desired array:

const desiredArray = [{
  name: 'Alex',
  age: 10,
  details: [{
    day: 'Monday',
    asst: 'Leo',
    subDetails: [{ color: 'green', qty: 85 }, { color: 'orange', qty: 35 }]
  }]
}]

This is my NodeJS get query:

router.get('/getByDay/:id/:day', async (req, res) => {
  try {
        const array = await getDay.find({_id: req.params.id  });

        res.json({ success: true, array })
  } catch (err) { res.json({ success: false, message: 'An error occured' }); }
});

5 Answers 5

1

You just need to filter out the nested array

array.map(item => ({...item, details: [item.details.find(detailsItem => detailsItem.day === "Monday")]}));
Sign up to request clarification or add additional context in comments.

Comments

1

Using map:

let array = [{
  name: 'Alex',
  age: 10,
  details: [{
    day: 'Monday',
    asst: 'Leo',
    subDetails: [{ color: 'green', qty: 85 }, { color: 'orange', qty: 35 }]
  },
  {
    day: 'Tuesday',
    asst: 'Shaun',
    subDetails: [{ color: 'brown', qty: 15 }, { color: 'indigo', qty: 35 }]
  },
  {
    day: 'Wednesday',
    asst: 'Julian',
    subDetails: [{ color: 'pink', qty: 25 }, { color: 'blue', qty: 15 }]
  },
  {
    day: 'Thursday',
    asst: 'Luis',
    subDetails: [{ color: 'peach', qty: 5 }, { color: 'black', qty: 15 }]
  },
  ]
}]

array = array.map(item => ({...item, details: item.details.filter(detail => detail.day === "Monday")}));
console.log(array)

2 Comments

This code works in javascript frontend. The desired array is not what I expected from Nodejs. router.get('/getByDay/:id/:eeid', async (req, res) => { try { const array = await getDay.find({_id: req.params.id }); desiredArray = array.map(item => ({...item, details: item.details.filter(detail => detail.day === "Monday")})); res.json({ success: true, desiredArray }) } catch (err) { res.json({ success: false, message: 'An error occured' }); } });
The desiredArray posted in the question would be the result of array.map(item => ({...item, details: item.details.filter(detail => detail.day === "Monday")}));. What difference do you see?
0

Just replace details with filter

array[0].details = array[0].details.filter(d => d.day == "Monday")

console.log(array);

Comments

0

This answer is for when requirements become a bit more complex (e.g. injecting data, sorting, etc). If that is the case I'd recommend you look into object-rewrite.

It might look a little complex at first, but I assure you everything has it's purpose here.

Works as following: (1) check which fields the client requested (2) determine which fields we need to load from the data store (3) request fields from the data store (4) modify data from data store to meet requested fields requirement (5) return response to client

Using plugins for (1) dynamically generated fields (2) removing fields or nested entities (3) sorting nested entities makes the code generic and much easier to manage

// const objectRewrite = require('object-rewrite');

const { filterPlugin, rewriter } = objectRewrite;

// substitute your own data store query here, making use of the fields if desired
const queryDataStore = (fields) => [{
  name: 'Alex',
  age: 10,
  details: [{
    day: 'Monday',
    asst: 'Leo',
    subDetails: [{ color: 'green', qty: 85 }, { color: 'orange', qty: 35 }]
  }, {
    day: 'Tuesday',
    asst: 'Shaun',
    subDetails: [{ color: 'brown', qty: 15 }, { color: 'indigo', qty: 35 }]
  }, {
    day: 'Wednesday',
    asst: 'Julian',
    subDetails: [{ color: 'pink', qty: 25 }, { color: 'blue', qty: 15 }]
  }, {
    day: 'Thursday',
    asst: 'Luis',
    subDetails: [{ color: 'peach', qty: 5 }, { color: 'black', qty: 15 }]
  }]
}];

// define your filter plugin
const filterByWeekDay = filterPlugin({
  name: 'filter-by-weekday',
  target: '*',
  requires: ['day'],
  fn: ({ value, context }) => value.day === context.weekday
});
// data store fields should come from your data model
const dataStoreFields = ['name', 'age', 'details.day', 'details.asst', 'details.subDetails.color', 'details.subDetails.qty'];
// define your rewriter with plugins
const rew = rewriter({ details: [filterByWeekDay] }, dataStoreFields);

// these come from the client request
const requestedFields = ['name', 'details.day', 'details.asst'];
const rewInstance = rew.init(requestedFields);
// get data from the data store
const data = queryDataStore(rewInstance.fieldsToRequest);
// data gets rewritten
rewInstance.rewrite(data, { weekday: 'Monday' });

// now return to the client
console.log(data);
// => [ { name: 'Alex', details: [ { day: 'Monday', asst: 'Leo' } ] } ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/[email protected]"></script>

Disclaimer: I'm the author of object-rewrite

Comments

-1

The straightforward way:

let desiredArray = array;
desiredArray[0].details = [desiredArray[0].details[0]];

const array = [{
  name: 'Alex',
  age: 10,
  details: [{
    day: 'Monday',
    asst: 'Leo',
    subDetails: [{ color: 'green', qty: 85 }, { color: 'orange', qty: 35 }]
  },
  {
    day: 'Tuesday',
    asst: 'Shaun',
    subDetails: [{ color: 'brown', qty: 15 }, { color: 'indigo', qty: 35 }]
  },
  {
    day: 'Wednesday',
    asst: 'Julian',
    subDetails: [{ color: 'pink', qty: 25 }, { color: 'blue', qty: 15 }]
  },
  {
    day: 'Thursday',
    asst: 'Luis',
    subDetails: [{ color: 'peach', qty: 5 }, { color: 'black', qty: 15 }]
  },
  ]
}]

let desiredArray = array;
desiredArray[0].details = [desiredArray[0].details[0]];

console.log(desiredArray);

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.