简体   繁体   English

在JavaScript中创建多维数组索引?

[英]Create multi-dimensional array index in Javascript?

I have a ajax request that is returning to me an object that looks roughly like the following: 我有一个ajax请求,该请求正在向我返回一个大致类似于以下内容的对象:

[
 {category: "Test Category", id: "1", name: "Test",  language: "English"},
 {category: "Test Category", id: "2", name: "Test2", language: "English"},
 {category: "A test",        id: "3", name: "Test3", language: "Spanish"},
 {category: "Test Category", id: "4", name: "Test4", language: "Spanish"}
]

Basically I need a way to do the following: 基本上,我需要一种方法来执行以下操作:

  • List all categories that exist in ONLY English or Spanish 列出仅以英语或西班牙语存在的所有类别
  • List all ID's that exist in a specified language 列出指定语言中存在的所有ID
  • List all ID's that exist in a specified category 列出指定类别中存在的所有ID

Now I'm fairly sure the best route to do this is to create my own temp arrays that can house that data but I'm not confident enough in Javascript to write the correct loop to get that data. 现在,我相当确定执行此操作的最佳方法是创建自己的临时数组以容纳该数据,但是我对Javascript不够自信,无法编写正确的循环来获取该数据。 I know in PHP I'd do something like $category['Test Category'][] = 3 while looping. 我知道在PHP中我会在循环时执行类似$category['Test Category'][] = 3

The idea is I need the ability to filter things based on the user selecting to filter by English and then by a category within that. 我的想法是,我需要能够根据用户选择按英语过滤,然后按其中的类别进行过滤的功能。

Can someone point me in the right direction? 有人可以指出我正确的方向吗?

Some ways to use underscore for your tasks: http://underscorejs.org 在任务上使用下划线的一些方法: http : //underscorejs.org

var data = [
 {category: "Test Category", id: "1", name: "Test",  language: "English"},
 {category: "Test Category", id: "2", name: "Test2", language: "English"},
 {category: "A test",        id: "3", name: "Test3", language: "Spanish"},
 {category: "Test Category", id: "4", name: "Test4", language: "Spanish"}
]

// Filter by spanish
var output = _.where(data, {"language":"Spanish"});

// Filter by category
var output = _.where(data, {"category":"A test"});

// List specific category ids
var output = _.pluck(_.where(data, {"category":"A test"}), "id");

// List category names
var output = _.pluck(_.where(data, {"language":"English"}), "category");

// Group by languages
var output = _.groupBy(data, function(value) { 
  return value.language
});
output["English"];

Since you included jQuery in the tag I thought I would use it: 由于您在标签中包含了jQuery,所以我认为我会使用它:

//All categories with English or spanish language (categories is the array)
$.grep(categories, function(c) { return c.language=='English' || c.language == 'Spanish'; });

Using vanilla JS, where json is your original array, you could use: 使用Vanilla JS(其中json是您的原始数组),可以使用:

function filterJson(attr, obj) {
    var attrList = [],
        match,
        tempAttr,
        i;

    for (i = 0; i < json.length; i += 1) {
        match = true;

        for (tempAttr in obj) {
            if (!obj[tempAttr].test(json[i][tempAttr])) {
                match = false;
                break;
            }
        }

        if (match) attrList.push(json[i][attr]);
    }

    return attrList;
}

And use it like this: 并像这样使用它:

"List all categories that exist in ONLY English or Spanish" “列出仅以英语或西班牙语存在的所有类别”

filterJson('category', {
    language: /(English|Spanish)/
});
// => ["Test Category", "Test Category", "A test", "Test Category"] 

"List all ID's that exist in a specified language" “列出指定语言中存在的所有ID”

filterJson('id', {
    language: /English/
});
// => ["1", "2"] 

"List all ID's that exist in a specified category" “列出指定类别中存在的所有ID”

filterJson('id', {
    category: /Test Category/
});  
// => ["1", "2", "4"] 

If you can count on a few assumptions about the data always being true -- eg, that you'll only ever have category:, id:, name:, and language:, and that there will never be a colon or comma anywhere in the name or category -- then I would actually suggest sticking all the information into single strings and use RegExp to find it. 如果您可以依靠一些关于数据始终为真的假设-例如,您将永远只有category:,id:,name:和language :,并且在其中的任何地方都不会出现冒号或逗号名称或类别-那么我实际上建议将所有信息粘贴到单个字符串中,并使用RegExp进行查找。

Eg: 例如:

[
 "category:Test Category, id:1, name:Test,  language:English",
 "category:Test Category, id:2, name:Test2, language:English",
 "category:A test,        id:3, name:Test3, language:Spanish",
 "category:Test Category, id:4, name:Test4, language:Spanish"
]

Now, to find a values for an entry, use RegExp.match(). 现在,要查找条目的值,请使用RegExp.match()。

var m = /^category:([^,]+)\s+id:(\d+),\s+name:([^,]+),\s+language:(.+)$/i;
// m[1] = Test Category
// m[2] = 1;
// m[3] = Test2
// m[4] = Spanish

And you can search by using tests. 您可以使用测试进行搜索。

function my_filter(criteria) {
    var results = [];
    var re = new RegExp(criteria);
    for (var i=0; i<array.length; i++) {
        if (array[i].test(re))
            results.push(array[i]);
    }
    return results;
}
var english_array = my_filter('language:english');
var atest_array = my_filter('category:a test');

The magic Google terms are "map" and "reduce". Google神奇的术语是“地图”和“减少”。

var data = [...the JSON data parsed with JSON.parse() if necessary...]

var categoriesInEnglish = data.reduce(function(accumulator, category) {
    if(category.language = 'English') {
        accumulator.push(category.id);
    }
});

see http://www.mrspeaker.net/2011/05/02/conventional-interfaces/ and http://www.mrspeaker.net/2011/04/27/reducing-map/ 参见http://www.mrspeaker.net/2011/05/02/conventional-interfaces/http://www.mrspeaker.net/2011/04/27/reducing-map/

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

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