过滤对象的对象并使用JavaScript中的最后7个对象创建新数组

时间:2021-04-18 22:57:01

How can I filter/loop an object of objects in JavaScript to create a new array with only the last 7 objects? I know there are similar posts, but nothing that I can find that really clarifies my specific requirements.

如何在JavaScript中过滤/循环对象对象以创建仅包含最后7个对象的新数组?我知道有类似的帖子,但我发现的任何内容都没有真正说明我的具体要求。

I assume one might want to use .length and push items into the array, but I am not sure how.

我假设有人可能想使用.length并将项目推送到数组中,但我不确定如何。

Also, sorting the array according to date would be essential in case the returned JSON is not already sorted.

此外,如果返回的JSON尚未排序,则必须根据日期对数组进行排序。

This is an example of the object of objects in JSON:

这是JSON中对象对象的示例:

"uptime": {
    "2017-05-03": {
      "failures": 816, 
      "successes": 18378
    }, 
    "2017-05-04": {
      "failures": 1067, 
      "successes": 22302
    }, 
    "2017-05-05": {
      "failures": 1008, 
      "successes": 82599
    }, 
    "2017-05-07": {
      "failures": 2724, 
      "successes": 142854
    }, 
    "2017-05-08": {
      "failures": 1329, 
      "successes": 149028
    }, 
    "2017-05-09": {
      "failures": 3072, 
      "successes": 155432
    }, 
    "2017-05-10": {
      "failures": 22260, 
      "successes": 313944
    }, 
    "2017-05-11": {
      "failures": 8056, 
      "successes": 591864
    }, 
    "2017-05-15": {
      "failures": 1722, 
      "successes": 111285
    }, 
    "2017-05-16": {
      "failures": 8832, 
      "successes": 251142
    }, 
    "2017-05-17": {
      "failures": 2620, 
      "successes": 170140
    }
}

1 个解决方案

#1


2  

You could simply take the values of your object ( the objects) and slice out the last seven from this:

您可以简单地获取对象(对象)的值并从中切出最后七个:

var arr = Object.values( input.uptime ).slice(-7);

However, object key order is not defined in any way, so you might want to sort the array:

但是,对象键顺序没有以任何方式定义,因此您可能希望对数组进行排序:

var arr=[];
for(key in input.uptime){
  input.uptime[key].time=key;
  arr.push(input.uptime[key]);
}

So now our array contains the objects with a time property, which can be sorted:

所以现在我们的数组包含带有time属性的对象,可以对它进行排序:

arr.sort((a,b)=>(new Date(a.time))-(new Date(b.time)));

And then sliced out:

然后切成:

arr=arr.slice(-7);

#1


2  

You could simply take the values of your object ( the objects) and slice out the last seven from this:

您可以简单地获取对象(对象)的值并从中切出最后七个:

var arr = Object.values( input.uptime ).slice(-7);

However, object key order is not defined in any way, so you might want to sort the array:

但是,对象键顺序没有以任何方式定义,因此您可能希望对数组进行排序:

var arr=[];
for(key in input.uptime){
  input.uptime[key].time=key;
  arr.push(input.uptime[key]);
}

So now our array contains the objects with a time property, which can be sorted:

所以现在我们的数组包含带有time属性的对象,可以对它进行排序:

arr.sort((a,b)=>(new Date(a.time))-(new Date(b.time)));

And then sliced out:

然后切成:

arr=arr.slice(-7);