简体   繁体   English

JS:对象的有序迭代

[英]JS: Ordered iteration of object

There is an object like this... 有一个像这样的东西...

{
  2016: {
    3 : [
      { field: "content 1" }
      { field: "content 2" }
    ]
    10 : [
      { field: "content 3" }
    ]
  }
  2017: {
    8 : [
      { field: "content 4" }
    ]
  }
}

...and I need to get access to the subelements in an ascending order. ...并且我需要以升序访问子元素。 That means I want to process 2016 object first, then 2017 object. 这意味着我要先处理2016对象,然后再处理2017对象。

Within that I need to process the month objects also in ascending order. 在此期间,我还需要按升序处理月份对象。

Iteration like... 迭代像...

for (var year in map) {
    if (map.hasOwnProperty(year)) {
        console.log(year)
    }
}

won't do the job properly. 将无法正常工作。

To get an ordered array of the content, recursively iterate the object, while getting the data by sorted keys, and using Array#concat to flatten the array. 要获取内容的有序数组,请递归地迭代对象,同时通过排序的键获取数据,并使用Array#concat展平数组。

 var data = {"2016":{"3":[{"field":"content 1"},{"field":"content 2"}],"10":[{"field":"content 3"}]},"2017":{"8":[{"field":"content 4"}]}}; function iterateByOrder(data) { var sorterKeys = Object.keys(data).sort(function(a, b) { return a - b; // sort by converting the keys to numbers }); return [].concat.apply([], sorterKeys.map(function(key) { // mapping the propeties to values, and flatting sub arrays return typeof data[key] === 'object' ? iterateByOrder(data[key]) : data[key]; })); } var result = iterateByOrder(data); console.log(result); 

We'll write a little analog of Array#forEach , which iterates over the key/value pairs in an object in sorted order, and calls a function on each pair, passing it the key and its value: 我们将编写一个类似于Array#forEach ,该类以排序的顺序遍历对象中的键/值对,并在每个对上调用一个函数,并向其传递键及其值:

function forEach(object, fn) {
  object.entries() . sort((a, b) => a[0] - b[0]) . forEach(pair => fn(...pair));
}

If you don't have Object#entries , the write it yourself: 如果您没有Object#entries ,请自己编写:

function objectEntries(object) {
  return Object.keys(object) . map(key => [key, object[key]]);
}

Now to iterate over your object: 现在遍历对象:

forEach(map, (year, yearValue) => 
  forEach(yearValue, (month, monthValue) => 
    console.log(`At ${year}/${month}, got data ${monthValue}`)));

Javascript objects aren't ordered, so the first thing you will need to do is to grab the keys, sort them, and then iterate in that order. Javascript对象不是有序的,因此您需要做的第一件事是获取键,对其进行排序,然后按该顺序进行迭代。

  data = { 2016: { 3 : [ { field: "content 1" }, { field: "content 2" }, ], 10 : [ { field: "content 3" }, ], }, 2017: { 8 : [ { field: "content 4" }, ], }, }; var keys = Object.keys(data); var sortedKeys = keys.sort(function(a, b) {return parseInt(a) - parseInt(b)}); for (var i = 0; i < sortedKeys.length; i++) { var key = sortedKeys[i]; console.log(data[key]); } 

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

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