Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

JavaScript -how to get array value with some condition?

I want to filter the let data array. I created map function with some condition for filter the let data array value to get the result ["true","false","true"] but I also want to display the let data array value when the result is true.

Here is my code:

 let data = 
{
    "days": {
        "Monday": {
            "checkin": "23:00",
            "checkout": "10:00"
        },
        "Tuesday": {
            "checkin": "07:00",
            "checkout": "14:00"
        },
        "Wednesdy": {
            "checkin": "07:00",
            "checkout": "04:00"
        },
    }
}
let day = ['Monday','Tuesday','Wednesdy'];
const ds = Object.keys(data.days);

const getin = (day) =day.map (d=> ds.indexOf(d)>=0 && data.days[d].checkin >= data.days[d].checkout); 


console.log("===Results===",getin);

JSFiddle Link

question from:https://stackoverflow.com/questions/65949524/javascript-how-to-get-array-value-with-some-condition

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If I'm not wrong, you want to filter then return all items matching condition.

You can use Object.entries along with .reduce to achieve it.

let data = 
{
    "days": {
        "Monday": {
            "checkin": "23:00",
            "checkout": "10:00"
        },
        "Tuesday": {
            "checkin": "07:00",
            "checkout": "14:00"
        },
        "Wednesdy": {
            "checkin": "07:00",
            "checkout": "04:00"
        },
    }
}
let day = ['Monday','Tuesday','Wednesdy'];
var result = Object.entries(data.days).reduce((acc, [key, value]) => {
  if(day.indexOf(key) >= 0 && value.checkin >= value.checkout)
    acc.push({[key]: value});
    
  return acc;
}, []); 
console.log(result);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...