我有一个带日期的对象数组。我想要做的是选择具有相同日期值的所有对象并将它们推入一个新数组 这是我的代码。
var posts = [
{
"userid": 1,
"rating": 4,
"mood": "happy",
"date": "2017-05-24T04:00:00.000Z"
},
{
"userid": 1,
"rating": 3,
"mood": "happy",
"date": "2017-05-24T04:00:00.000Z"
},
{
"userid": 1,
"rating": 3,
"mood": "angry",
"date": "2017-05-25T04:00:00.000Z"
},
{
"userid": 1,
"rating": 5,
"mood": "hungry",
"date": "2017-05-25T04:00:00.000Z"
}]
var may25=[];
for(i=0;i < posts.length;i++){
if(posts[i].date === posts[i].date){
may25.push(posts[i].date)
}
}
答案 0 :(得分:0)
如果您只是寻找可能25个日期(正如您的问题所示):
var may25=[];
for (i=0;i < posts.length;i++) {
if (posts[i].date === "2017-05-25T04:00:00.000Z") {
may25.push(posts[i].date)
}
}
答案 1 :(得分:0)
您可能想要创建一个包含date =&gt;的对象。事件数组:
var result=posts.reduce((obj,event)=>((obj[event.date]=obj[event.date] || []).push(event),obj),{});
现在你可以做到:
result["2017-05-25T04:00:00.000Z"].forEach(console.log);
工作原理:
posts.reduce((obj,event)=>...,{}) //iterate over the posts and pass each as event to the function and also pass an object to be filled
(obj[event.date]=obj[event.date] || [])//return the date array, or create a new one if it doesnt exist
.push(event)//append our event to it
答案 2 :(得分:0)
您可以从字符串中剪切日期,并将其作为对象的键,以便按日期对项目进行分组。结果是一个包含所有分组对象的对象。
var posts = [{ userid: 1, rating: 4, mood: "happy", date: "2017-05-24T04:00:00.000Z" }, { userid: 1, rating: 3, mood: "happy", date: "2017-05-24T04:00:00.000Z" }, { userid: 1, rating: 3, mood: "angry", date: "2017-05-25T04:00:00.000Z" }, { userid: 1, rating: 5, mood: "hungry", date: "2017-05-25T04:00:00.000Z" }],
groups = Object.create(null);
posts.forEach(function (o) {
var date = o.date.slice(0, 10);
groups[date] = groups[date] || [];
groups[date].push(o)
});
console.log(groups);
.as-console-wrapper { max-height: 100% !important; top: 0; }