Issue
Question : filter the json array and get the following
1: All entries with name "Sam".
2: All entries with date "dec 2019".
// json Data below.
var arr = [{
"id":"27",
"0":{
"name":"Sam",
"date":"2021-02-28"
},
"1":{
"name":"Mark",
"date":"2019-12-08"
}
},{
"id":"30",
"0":{
"name":"Sam",
"date":"2019-12-11"
}
}
]
// code :
function filter(){
var filtered = [];
for (let i = 0 ; i < arr.length ; i++){
filtered = [];
for(let x in arr){
if(typeof(arr[x] == "object")){
for(let k in arr[x]){
filtered.push({name : arr[x][k].name,date:arr[x][k].date})
}
}
}
}
return filtered
}
function main(){
var filter_date = [];
var filter_name = [];
var arr1 = filter()
for(let i in arr1){
if(arr1[i].name == "Sam"){
filter_name.push(arr1[i])
}
i need to compare the dates if the dates are matching with if statement without hardcoding them
if(arr1[i].date == "2019-12-11" || arr1[i].date == "2019-12-08"){
filter_date.push(arr1[i])
}
}
// arr1.filter(item =>{
// console.log(item)
// })
console.log("the values with name SAM = ",filter_name)
console.log("the values with name date Dec = ",filter_date)
}
main()
Solution
You could use Array.flatMap(), Object.Values and Array.filter() to return the desired result.
Inside the filter() call, we'll return true if name is Sam or the month is December.
We can modify the filter function as needed.
const arr = [{ "id":"27", "0":{ "name":"Sam", "date":"2021-02-28" }, "1":{ "name":"Mark", "date":"2019-12-08" } },{ "id":"30", "0":{ "name":"Sam", "date":"2019-12-11" } } ]
// Change as required. Currently matches name === 'Sam' or month is December
const filterFunction = ({ name, date }) => {
return (name === 'Sam') || (date + '').split('-')[1] === '12';
};
const result = arr.flatMap(Object.values).filter(filterFunction);
console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; }
Answered By - Terry Lennox
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.