简体   繁体   English

如何遍历并将JSON对象放入javascript数组中?

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

I am developing an application in javascript. 我正在使用javascript开发应用程序。 Here is my PHP code: 这是我的PHP代码:

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. 所以基本上我只接受对象的idstartend元素,并将它们作为JSON回显到数组中。 How would I be able to do the same in javascript foreach loop considering that var requests is the object containing all the data? 考虑到var请求是包含所有数据的对象,我如何在javascript foreach循环中执行相同的操作?

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. 注意,除了idstartend之外,请求中还包含其他数据,例如pricestatus ,但是我只想使用idstartend包含在我的events[]数组中。

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? 如果我只需要显示id> 50的请求,我可以怎么办? How do I use if statement here? 如何在此处使用if语句?

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. 有点ES6。 Because ES6 is gorgeous. 因为ES6很漂亮。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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