基于第一个索引过滤二维javascript数组

Filtering two-dimensional javascript array based on 1st index

本文关键字:二维 javascript 数组 第一个 索引 过滤      更新时间:2023-09-26

我有以下javascript数组代码,它定义了一些项:

product[17564] =    Array;
product[17564][1245] = ['BL-2810', 'text1']; 
product[17564][1246] = ['BL2810AB', 'text2']; 
product[17564][1247] = ['BL2810AN', 'text3']; 
product[17563] =    Array;
product[17563][1238] = ['BK-2810', 'text4']; 
product[17563][1239] = ['BK2810AB', 'text5']; 
product[17565] =    Array;
product[17565][1253] = ['CK-2810', 'text6']; 
product[17565][1254] = ['CK2810AN', 'text7']; 

我想根据用户动态设置的"product"数组的第一个索引来筛选项目。例如,如果用户集编号是"17563",那么我想过滤以下以"17563"为第一索引的项目:

product[17563][1238]
product[17563][1239]

并仅在后面的代码中使用这些项。谢谢

似乎有产品类别,每个类别中都有一些产品。

看起来类别和产品也有一种id,您将其用作数组索引。

我认为您没有使用正确的数据结构来存储数据。

如果您只有3个id为17883、17884和17885的类别,会发生什么?您将以17886个(计数位置0)位置的数组结束,只需使用其中的3个。

您要做的是创建一个存储类别信息和产品信息的对象,然后用这些对象填充数组。

例如:

var categories = new Array();
var category1 = new Object();
category1.id = 17883;
category1.products = new Array();
categories[0] = category1;
var product1 = new Object();
product1.id = 1233;
product1.code = 'BK-404';
product1.name = 'text3';
category1.products[0] = product1;
// and so on

要读取您要做的信息:

var userInput = //receive user input
for(var i = 0; i < categories.length; i++){
    if(categories[i].id == userInput){
        return categories[i].products;
    }
    return null; //category not found
}

感谢您的帮助,它为我提供了使用json对象的线索。事实上,我有产品数据和每个产品的一些变体,带有属性(即,与类别和带有属性的产品类似的逻辑,如答案所示)。

最终,我json编码了我的初始php数组("$array"),从中我获得了数据,

$array_json=json_encode($array);

并将其传递给javascript(这是通过smarty完成的,因为我在应用程序中使用smarty模板)。

$smarty->assign('array_json', $array_json);

然后在smarty模板文件中,我用smarty数组创建了一个javascript数组:

var prd_array={$array_json};

并继续:

for (var product_id in prd_array) {
            if(product_id == id) {
                for (var variant_id in prd_array[product_id]) {                     
                    for (var some_attribute_id in prd_array[product_id][variant_id].attributes)     {                           
                        var variant_title = prd_array[product_id][variant_id].attributes[some_attribute_id].attribute_name;                         
                        document.myfrm.myselect.options[document.myfrm.myselect.options.length]=new Option("variant_title, variant_id, true, false);                             
                    }
                }
                break;
            }               
        } 

为了解释以上内容,我使用嵌套循环迭代到多维数组的更深层次,以便获得用户所选产品变体的一些属性值。'id'是用户选择的产品id值,将其与每个product_id值进行比较,当匹配时,迭代特定产品的变体及其atttributes属性,该属性总是具有索引为some_attribute_id的单个元素,并且它的属性之一是CCD_ 5,其是要用于在动态填充的选择菜单中显示的值之一(连同CCD_。