0

I am developing an application in javascript. Here is my PHP code:

events: [
foreach($requests as $request)
                {
                    if($request->accepted == 'yes') {
                echo 
                "{
                        id: ". $request->id . ",
                        start:'". $request->start . "',
                        end: '". $request->end . "',
                    },";
                    }
]

So basically I am taking only id, start and end elements of the object and echoing them as JSON in an array. How would I be able to do the same in javascript foreach loop considering that var requests is the object containing all the data?

NOTE that there is also other data in requests such as price, status in addition to id, start, end but I only want to use id , start and end to be included in my events[] array.

2 Answers 2

3

try this (assuming that requests is the object array)

var events = requests.map(function(obj){
 return { id : obj.id, start : obj.start, end : obj.end }
})

Can you please suggest what do I do incase i need to show only the requests where id > 50? How do I use if statement here?

var events = requests.filter(function(){
  if (index >= 50 ) return false;
}).map(function(obj, index){
  return { id : obj.id, start : obj.start, end : obj.end }
});
Sign up to request clarification or add additional context in comments.

4 Comments

will it include all the requests in the events array?
Thank you. Can you please suggest what do I do incase i need to show only the requests where id > 50? How do I use if statement here?
if (index >= 50 ) return false; would not help You to filter the array, but rather fills it with falses.
@РоманПарадеев I have edited the answer to fix this. Thanks for pointing it out.
0

A bit of ES6. Because ES6 is gorgeous.

requests
  .filter(x => x.id > 50)
  .map(({id, start, end}) => ({id, start, end}))

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.