Reputation: 269
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.
Upvotes: 0
Views: 61
Reputation: 68413
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 }
});
Upvotes: 3
Reputation: 4266
A bit of ES6. Because ES6 is gorgeous.
requests
.filter(x => x.id > 50)
.map(({id, start, end}) => ({id, start, end}))
Upvotes: 0