Javascript:在_.each循环中对已解析的JSON进行排序 [英] Javascript: Sorting Parsed JSON within _.each loop
问题描述
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屋!