简体   繁体   中英

How to loop over and put JSON objects in an array in javascript?

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.

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 }
});

A bit of ES6. Because ES6 is gorgeous.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM