Javascript:在_.each循环中对已解析的JSON进行排序 [英] Javascript: Sorting Parsed JSON within _.each loop

查看:112
本文介绍了Javascript:在_.each循环中对已解析的JSON进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var Bible = JSON.parse( fs.readFileSync(bible.json, 'utf8') ); _.each(Bible, function (b, Book) { return Book; });

var Bible = JSON.parse( fs.readFileSync(bible.json, 'utf8') ); _.each(Bible, function (b, Book) { return Book; });

这将从圣经中输出每本书的名称(例如创世纪,出埃及记,利未记等).问题是JSON文件中的书不整齐.我试图以各种方式对它们进行排序,但是在_.each循环内似乎没有任何可能.当我这样做时:

This outputs each book name from the Bible (ex. Genesis, Exodus, Leviticus, etc.). The problem is that the books from the JSON file are not in order. I have tried to sort them in various ways, but nothing seems possible inside of the _.each loop. When I did this:

correctlyOrderedList.indexOf(Book) - correctlyOrderedList.indexOf(b);

它正确返回了每个索引,但是据我所知,我仍然无法对).each循环中的索引进行排序.有没有一种方法可以在_.each循环之前对其进行排序,或者可以在其中进行排序?

It returned the index of each one correctly, but I still can't sort those within the ).each loop as far as I am aware. Is there a way to order it prior to the _.each loop or is there a way to sort it within?

推荐答案

您不能在each内进行排序,因为那将为时已晚. 但是您可以在使用_.each之前进行排序:

You cannot sort inside each because that would be too late. But you can sort before using _.each:

var Bible = JSON.parse( fs.readFileSync(bible.json, 'utf8') );
Bible.sort(); // sorts in place
_.each(Bible, function (b, Book) { 
  return Book; 
});

或将排序后的值作为参数传递给each:

Or pass the sorted value as a parameter to each:

var Bible = JSON.parse( fs.readFileSync(bible.json, 'utf8') );
_.each(Bible.sort(), function (b, Book) { 
  return Book; 
});

这篇关于Javascript:在_.each循环中对已解析的JSON进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆