Reputation: 3359
I am trying to implement the solution to find data from JSON by date here is the JSON data
[
{
draw_date: "2021-06-30T00:00:00.000",
winning_numbers: "24 29 50 65 66 14",
multiplier: "4"
},
{
draw_date: "2021-06-26T00:00:00.000",
winning_numbers: "08 31 39 43 60 17",
multiplier: "3"
}
];
I have implemented the solution
const result = [
{
draw_date: "2021-06-30T00:00:00.000",
winning_numbers: "24 29 50 65 66 14",
multiplier: "4"
},
{
draw_date: "2021-06-26T00:00:00.000",
winning_numbers: "08 31 39 43 60 17",
multiplier: "3"
}
];
const date = result.find(data => data.draw_date == '2021-06-30T00:00:00.000')
console.log(date);
But the solution is only finding the data by exact date string for example
2021-06-30T00:00:00.000
If I search like this
2021-06-30
Getting undefind
Any idea? Please help.
Upvotes: 0
Views: 78
Reputation: 56
You are calling filtering on the basis of 2021-06-30T00:00:00.000
, if it matches in the array you will get a response.
For the solution you can use the below code:
const result = [
{
draw_date: "2021-06-30T00:00:00.000",
winning_numbers: "24 29 50 65 66 14",
multiplier: "4"
},
{
draw_date: "2021-06-26T00:00:00.000",
winning_numbers: "08 31 39 43 60 17",
multiplier: "3"
}
];
const date = result.find(data => data.draw_date == '2021-06-30T00:00:00.000' || data.draw_date.split("T")[0] == '2021-06-30');
Or
cost date = result.find(data => data.draw_date.split("T")[0] == '2021-06-30');
Output :
{draw_date: "2021-06-30T00:00:00.000", winning_numbers: "24 29 50 65 66 14", multiplier: "4"}
Alternatives :
includes
which can check if the string matches or notloadash(underscore.js)
as well to fetch and organize JSONUpvotes: 1
Reputation: 1816
There is no string == "2021-06-30"
in your data. The first string called draw_date
is 2021-06-30T00:00:00.000
, which is clearly not the same string.
You will need to use an expression to match a string that starts with the searched date string.
It appears the date format is well-defined, and if you can rely on that, then perhaps startsWith
might be helpful: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
Upvotes: 1
Reputation: 31
There's a difference between 2021-06-30T00:00:00.000
and 2021-06-30
when using the equality operator (==
). Instead of searching, you're checking if those two values are equal, which they are not.
What you want to use is indexOf
.
const date = result.find(data => data.draw_date.indexOf('2021-06-30'))
console.log(date);
Upvotes: 1
Reputation: 9953
You can use includes
as below
const result = [
{
draw_date: "2021-06-30T00:00:00.000",
winning_numbers: "24 29 50 65 66 14",
multiplier: "4"
},
{
draw_date: "2021-06-26T00:00:00.000",
winning_numbers: "08 31 39 43 60 17",
multiplier: "3"
}
];
const date = result.find(data => data.draw_date.includes('2021-06-30'))
console.log(date);
Upvotes: 1