Is there a way to sort through an array based on a nested value?

Within an array of objects, I have a structure like this:

"times": [{
  "id" : "id",
    "name" : "place",
    "location" : "place",
    "hours" : [
    {"day": "Sunday", "day_id": 0,
  "tags": "" },
    {"day": "Monday", "day_id": 1,
"tags": "" },
    {"day": "Tuesday", "day_id": 2,
"tags": "" },
    {"day": "Wednesday", "day_id": 3,
"tags": "" },
    {"day": "Thursday", "day_id": 4,
"tags": "" },
    {"day": "Friday", "day_id": 5,
"tags": "" },
    {"day": "Saturday", "day_id": 6,
"tags": "" }
    ]
    }
    ]

My goal is to extract specific data from the hours array within each object.

I am attempting to identify and retrieve objects that match a particular day_id in the hours array.

My initial attempt was this:

let f1 = times.filter((item: { id: string; hours: { day_id : number;};}) => item.hours.day_id == 0 );

However, this approach did not yield the desired result. What mistake am I making here?

Answer №1

By encapsulating the code above within a JSON object like so:

const obj = {
  "times": [
    {
      "id": "id",
      "name": "place",
      "location": "place",
      "hours": [
        { "day": "Sunday", "day_id": 0, "tags": "" },
        { "day": "Monday", "day_id": 1, "tags": "" },
        { "day": "Tuesday", "day_id": 2, "tags": "" },
        { "day": "Wednesday", "day_id": 3, "tags": "" },
        { "day": "Thursday", "day_id": 4, "tags": "" },
        { "day": "Friday"", "day_id": 5, "tags": "" },
        { "day": "Saturday", "day_id": 6, "tags": "" }
      ]
    }
  ]
};

A function can be implemented to filter the hours sub-array based on day_id as follows:

function extractHoursByDayId(obj, dayId) {
  return obj.times.map(item => ({
    ...item,
    hours: item.hours.filter(hour => hour.day_id === dayId)
  }));
}

Keep in mind that this specifically isolates an entry from the hours sub-array while leaving other elements untouched. To filter objects within the times array instead, you can utilize the following method:

function extractTimesByDayId(obj, dayId) {
  return obj.times.filter(item => item.hours.some(hour => hour.day_id === dayId));
}

Answer №2

It seems like you're having trouble with understanding the question. However, it appears that you are attempting to sort through the times array retrieved from a JSON file. Let's assign this array to a variable.

let dataSet = your json data (times) here

Now that we have assigned it to a variable, you want to filter the hours array within each item of the times array. This requires using a nested filter function:

dataSet.times.filter(({hours}) => {
 return hours
  .filter(({day_id}) => day_id === 0)
})

Answer №3

If you're looking to retrieve specific data based on day_id, the code snippet below should do the trick:

interface Hour {
  day: string;
  day_id: number;
  tags: string;
}

interface Time {
  id: string;
  name: string;
  location: string;
  hours: Hour[];
}

const times: Time[] = [{
  id: "id",
  name: "place",
  location: "place",
  hours: [
    { day: "Sunday", day_id: 0, tags: "" },
    { day: "Monday", day_id: 1, tags: "" },
    { day: "Tuesday", day_id: 2, tags: "" },
    { day: "Wednesday", day_id: 3, tags: "" },
    { day: "Thursday", day_id: 4, tags: "" },
    { day: "Friday", day_id: 5, tags: "" },
    { day: "Saturday", day_id: 6, tags: "" }
  ]
}];

let filteredTimes = times.filter(item => item.hours.some(hour => hour.day_id === 0));
console.log(filteredTimes);

Answer №4

Your current method has a small flaw in that 'hours' is an array, meaning you must loop through each element in the hours array to verify the day_id. Moreover, since 'hours' is an array of objects, you cannot directly access day_id on item.hours. You have to iterate over each hour object and then inspect its day_id.

let filteredHours = times.filter((item) => {
// Check if any hour object in the hours array matches the desired day_id
return item.hours.some((hour) => hour.day_id === 0);});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using ThreeJS to project a texture onto a mesh surface

I am trying to project a texture onto the surface of a mesh using ThreeJS. The link provided achieves the desired result, although I am uncertain about the method used to accomplish it. . As I continue my research, I will update this post. If anyone has ...

JavaScript: Passing the "this" object in an AJAX request situation

Here is the code snippet I am working with: $(function(){ $("#CASA").click(function(){ rsExecute("rs/rs_luci.php","premi",1,function(cc){}); var col=$( this ).css( "background-color" ); se ...

Establish a connection to the ActiveMQ broker utilizing STOMP protocol in an Ionic application

I've recently received an Ionic + Capacitor app that is primarily meant to run on the Android platform. My current task is to incorporate communication with a remote ActiveMQ broker into the app. To achieve this, I utilized the STOMP JS library which ...

How can a "Loading" message be displayed while external JavaScript is loading?

I have mastered the art of using JS or jQuery to showcase a "Loading" message during the loading process. Currently, I am working on a sizeable web application that relies on various JS dependencies, and I am seeking a way to exhibit a "loading" message wh ...

Retrieve ag grid from TypeScript file

I am currently utilizing ag-grid-angular in my Angular application to showcase data. I have a button that is located outside the ag grid, and when it is clicked, I need to retrieve all row data from the grid. I am aware that there is an API available for a ...

Ways to update the dataTable in ReactJS post clicking the save button on the modal

Just starting my second week of diving into React. Looking for some guidance on how to update the dataTable in reactJs after clicking the save button in the modal. This is the structure I'm working with: I have a ParameterMaintenance.jsx file that ...

After refreshing, the LocalStorage in Angular 2 seems to disappear

Something a little different here :) So, when attempting to log a user in, I am trying to store the access_token and expires in localStorage. It seems to be working "okay". However, if I refresh the page, the tokens disappear. Also, after clicking the log ...

How can I remove specific items from a PrimeNG PickList?

Currently, I'm working on a page where updates are made using PrimeNG PickList. The initial state of the target list is not empty, but when selected items are moved from source to target list, they are not removed from the source list as expected. Fr ...

The ajaxForm function is failing to execute properly and is not providing any error messages

When trying to use jQuery ajaxForm, I encounter a strange issue. I am attempting to set up a form for file upload with progress percentage tracking. However, my ajaxForm function does not seem to be triggering at all. Below is the code snippet I am usin ...

I have implemented a bootstrap modal, but whenever I trigger a function on the JavaScript side, it automatically closes. I am aiming for the modal to remain open

<div id="responsive-modal3" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none; " data-keyboard="false" data-backdrop="static" ng-init = "populateBidSpocData()" > <div cl ...

Error message: "Encountered a template parsing error stating that the element 'ngb-carousel' is not recognized."

Initially, I created a fresh project using the Angular CLI by running this command: ng new my-project Next, I followed the instructions in the angular-cli readme to install Bootstrap 4. After that, I installed NG Bootstrap. Then, I generated a new comp ...

Performing double string splitting with multiple separators in javascript

If I have a string like a.b.c.d#.e.f.g.h#.i.j.k.l and want to split it first by "#" and then by ".": str = a.b.c.d#.e.f.g.h#.i.j.k.l res = str.split("#") res[0] will contain a.b.c.d after the first split. Now, I need to further split this data. Is th ...

Angular ng-repeat is incompatible with the JSON parser

I am facing an issue with accessing JSON objects and setting values into Angular Ui-grid. The problem arises when some of the fields in my JSON object are actually JSON strings. I attempted to convert these fields into JSON objects using JSON.parser, but e ...

Guide on redirecting to a new domain using a cookie in Express.js

I am working on a web app using Express on Node and I want to add a proxy login feature that allows users to be automatically logged in and redirected to another site after logging into my site. Within my routing function, I have the following code: res ...

Error-throwing constructor unit test

In my code, I have implemented a constructor that takes in a configuration object. Within this constructor, I perform validations on the object. If the validation fails, I aim to throw an error that clearly describes the issue to the user. Now, I am wonde ...

Utilizing JavaScript regex to remove substrings that contain parentheses

I am working with a string variable named myString that includes some unwanted content towards the end: var myString = 'The sentence is good up to here foo (bar1 bar2)'; var toBeRemoved = 'foo (bar1 bar2)'; I am looking for the best w ...

Material UI Input Field, Present Cursor Location

Is there a way to retrieve the current cursor (caret) position in a MaterialUI text field? https://material-ui.com/components/text-fields/ I am looking to make changes to the string content at a specific index, such as inserting a character X between cha ...

What is the best way to move the numerical range value into a span element?

How can I implement the "update" function to retrieve the current slider value and transfer it to a Meter element with the message "Value: [current value]". The indicator color should be #ffff00 if the current value is at least 85, otherwise, it should b ...

Node accurately handles and displays errors, such as validation errors, in a precise manner

I am currently restructuring our code base to incorporate promises. Below are two blocks of sample code: user.service.js export function updateUserProfileByUsername(req, res) { userController.getUserByUsername(req.params.username) .then((userProfile ...

Generate a 3D numpy array consisting of either three 2D numpy arrays or three 1D numpy arrays

I have three numpy 2D arrays that contain True or False values: A1 has a shape of (x * y) A2 has a shape of (x * z) A3 has a shape of (y * z) Now, I am looking to create a 3D array with a shape of (x * y * z) where each element is calculated as follows: 3 ...