在 js 中过滤 json 结果

从 json 调用的结果中过滤数据


我正在尝试在将 JSON 数据提供给 dataTables 之前对其进行预处理。原因是我需要将源数据分成 3 个数据表。我可以在 Java 的服务器端执行此操作,但这种方法是不可取的。请不要问为什么,这只是由于负载平衡计算。


 type: "GET",

            dataType: 'json',

            contentType: 'application/json',

            success: function (data) {

                console.log(data);

                var table = $('#tbl1');

                var tableUsul = $('#tbl1Terima');

                var tableTolak = $('#tbl2Tolak');



                table.DataTable({

                    "data": data.object, // i want to maipulate this

                    "processing": true,

                    "destroy": true,

                    "pagingType": "numbers",

                    "columns": [

                        {"data": null, "class": "rowCenter"},

                        {"data": "0"},

                        {"data": "1"},

                        {"data": "2"}

                    ........


console.log(data.object) 结果


[

[1,"myname1","1000"],

[0,"myname2","0"],

[1,"myname5","12121"],

[1,"myname2","23455"]

]

我想过滤 data.object。所以在数据库中,第一列由 1 和 0 组成,我想只显示 1 或只显示 0。我试图使用data.filter(function(){})但 js 无法识别功能过滤器。


SMILET
浏览 234回答 2
2回答

FFIVE

您可以尝试以下操作。var data = [[1,"myname1","1000"],[0,"myname2","0"],[1,"myname5","12121"],[1,"myname2","23455"]];var newArray = [];for (i = 0; i < data.length; i++) {&nbsp;var&nbsp; element = data[i];&nbsp;if(element[0] == 1){&nbsp;&nbsp; &nbsp;newArray.push(element);}}console.log(newArray)

HUX布斯

您可以尝试以下操作:let data = [[1,"myname1","1000"],[0,"myname2","0"],[1,"myname5","12121"],[1,"myname2","23455"]];function group2DArrayDataByIndex(dataArr, groupByIndex) {&nbsp; let groupedData = dataArr.reduce(function (acc, arr) {&nbsp; &nbsp; if (Array.isArray(arr) && (arr[groupByIndex] !== undefined || arr[groupByIndex] !== null)) {&nbsp; &nbsp; &nbsp; let key = arr[groupByIndex];&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; if (Array.isArray(acc[key])) {&nbsp; &nbsp; &nbsp; &nbsp; acc[key].push(arr);&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; acc[key] = [arr];&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return acc;&nbsp; }, {});&nbsp;&nbsp;&nbsp; return groupedData;}let groupByIndex = 0;let groupedData = group2DArrayDataByIndex(data, groupByIndex);console.log(groupedData);console.log(groupedData[0]); //access data with only 0console.log(groupedData[1]); //access data with only 1它的作用:此代码根据提供的用于分组数据的索引对数据(数组数组)进行分组。所有分组的数据都存储在一个对象中,这样您就可以访问任何数据而无需再次分组/过滤。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript