JavaScript中的多维关联数组

问题描述 投票:70回答:10

有以下查询结果:(key1和key2可以是任何文本)

id   key1     key2     value

1    fred     apple    2
2    mary     orange   10
3    fred     banana   7
4    fred     orange   4
5    sarah    melon    5
...

我希望将数据存储在网格中(可能作为一个数组)循环所有记录,如下所示:

         apple    orange   banana  melon
fred        2        4         7     -
mary        -        10        -     -
sarah       -        -         -     5

在PHP中,使用关联数组非常简单:

$result['fred']['apple'] = 2;

但在像这样的JavaScript关联数组中不起作用。阅读了大量的教程后,我能得到的就是:

arr=[];
arr[1]['apple'] = 2;

arr['fred']['apple'] = 2;不起作用。我尝试过对象数组,但对象属性不能是自由文本。我阅读教程越多,我就越困惑......

欢迎任何想法:)

javascript multidimensional-array associative-array
10个回答
137
投票

只需使用常规JavaScript对象,它将以与关联数组相同的方式“读取”。你必须记住首先初始化它们。

var obj = {};

obj['fred'] = {};
if('fred' in obj ){ } // can check for the presence of 'fred'
if(obj.fred) { } // also checks for presence of 'fred'
if(obj['fred']) { } // also checks for presence of 'fred'

// The following statements would all work
obj['fred']['apples'] = 1;
obj.fred.apples = 1;
obj['fred'].apples = 1;

// or build or initialize the structure outright
var obj = { fred: { apples: 1, oranges: 2 }, alice: { lemons: 1 } };

如果您正在查看值,您可能会看到如下内容:

var people = ['fred', 'alice'];
var fruit = ['apples', 'lemons'];

var grid = {};
for(var i = 0; i < people.length; i++){
    var name = people[i];
    if(name in grid == false){
        grid[name] = {}; // must initialize the sub-object, otherwise will get 'undefined' errors
    }

    for(var j = 0; j < fruit.length; j++){
        var fruitName = fruit[j];
        grid[name][fruitName] = 0;
    }
}

0
投票
    var myObj = [];
    myObj['Base'] = [];
    myObj['Base']['Base.panel.panel_base'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
                                              Align:'',  AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
    myObj['Base']['Base.panel.panel_top']  = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
                                              Align:'',AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };

    myObj['SC1'] = [];
    myObj['SC1']['Base.panel.panel_base'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
                                              Align:'',  AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
    myObj['SC1']['Base.panel.panel_top']  = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
                                              Align:'',AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };


    console.log(myObj);

    if ('Base' in myObj) {
      console.log('Base found');

      if ('Base.panel.panel_base' in myObj['Base'])  {
        console.log('Base.panel.panel_base found'); 


      console.log('old value: ' + myObj['Base']['Base.panel.panel_base'].Context);  
      myObj['Base']['Base.panel.panel_base'] = 'new Value';
      console.log('new value: ' + myObj['Base']['Base.panel.panel_base']);
      }
    }

输出:

  • 找到基地
  • 找到了Base.panel.panel_base
  • 旧价值:基数
  • 新价值:新价值

阵列操作有效。没有问题。

迭代:

     Object.keys(myObj['Base']).forEach(function(key, index) {            
        var value = objcons['Base'][key];                   
      }, myObj);

21
投票

如果它不必是一个数组,你可以创建一个“多维”JS对象......

<script type="text/javascript">
var myObj = { 
    fred: { apples: 2, oranges: 4, bananas: 7, melons: 0 }, 
    mary: { apples: 0, oranges: 10, bananas: 0, melons: 0 }, 
    sarah: { apples: 0, oranges: 0, bananas: 0, melons: 5 } 
}

document.write( myObject[ 'fred' ][ 'apples' ] );
</script>

10
投票

Javascript很灵活:

var arr = {
  "fred": {"apple": 2, "orange": 4},
  "mary": {}
  //etc, etc
};

alert(arr.fred.orange);
alert(arr["fred"]["orange"]);
for (key in arr.fred)
    alert(key + ": " + arr.fred[key]);

8
投票

因为我需要以一种很好的方式获得所有元素,所以我遇到了这个SO主题“遍历2维关联数组/对象” - 无论我的名字是什么,因为功能很重要。

var imgs_pl = { 
    'offer':        { 'img': 'wer-handwritter_03.png', 'left': 1, 'top': 2 },
    'portfolio':    { 'img': 'wer-handwritter_10.png', 'left': 1, 'top': 2 },
    'special':      { 'img': 'wer-handwritter_15.png', 'left': 1, 'top': 2 }
};
for (key in imgs_pl) { 
    console.log(key);
    for (subkey in imgs_pl[key]) { 
        console.log(imgs_pl[key][subkey]);
    }
}

3
投票

当属性名称是整数时,获取关联数组属性的值:

从关联数组开始,其中属性名称是整数:

var categories = [
    {"1":"Category 1"},
    {"2":"Category 2"},
    {"3":"Category 3"},
    {"4":"Category 4"}
];

将项目推送到数组:

categories.push({"2300": "Category 2300"});
categories.push({"2301": "Category 2301"});

循环遍历数组并使用属性值执行某些操作。

for (var i = 0; i < categories.length; i++) {
    for (var categoryid in categories[i]) {
        var category = categories[i][categoryid];
        // log progress to the console
        console.log(categoryid + " : " + category);
        //  ... do something
    }
}

控制台输出应如下所示:

1 : Category 1
2 : Category 2
3 : Category 3
4 : Category 4
2300 : Category 2300
2301 : Category 2301

如您所见,您可以绕过关联数组限制并使属性名称为整数。

注意:我的示例中的关联数组是序列化Dictionary []对象时的json。


3
投票

看来,对于某些应用程序,javascript中有一种更简单的多维关联数组方法。

  1. 鉴于所有数组的内部表示实际上都是对象的对象,已经表明数字索引元素的访问时间实际上与关联(文本)索引元素的访问时间相同。
  2. 第一级关联索引元素的访问时间不会随着实际元素数量的增加而增加。

鉴于此,可能存在许多情况,其中使用连接字符串方法来创建多维元素的等效性实际上更好。例如:

store['fruit']['apples']['granny']['price] = 10
store['cereal']['natural']['oats']['quack'] = 20

去:

store['fruit.apples.granny.price'] = 10
store['cereal.natural.oats.quack'] = 20

优点包括:

  • 无需初始化子对象或弄清楚如何最好地组合对象
  • 单级访问时间。对象内的对象需要N倍的访问时间
  • 可以使用Object.keys()来提取所有维度信息和..
  • 可以使用函数regex.test(string)和键上的array.map函数来准确地提取出你想要的东西。
  • 维度中没有层次结构。
  • “点”是任意的 - 使用下划线实际上使正则表达式更容易
  • 有很多脚本可以将JSON“展平”成这种格式
  • 可以在密钥列表上使用所有其他不错的数组处理函数

3
投票

不要使用数组,使用对象。

var foo = new Object();

1
投票

您不需要使用对象,您可以使用普通的多维数组进行操作。

这是我没有对象的解决方案:

// Javascript
const matrix = [];

matrix.key1 = [
  'value1',
  'value2',
];

matrix.key2 = [
  'value3',
];

在PHP中相当于:

// PHP
$matrix = [
    "key1" => [
        'value1',
        'value2',
    ],
    "key2" => [
        'value3',
    ]
];

0
投票

<script language="javascript">

// Set values to variable
var sectionName = "TestSection";
var fileMap = "fileMapData";
var fileId = "foobar";
var fileValue= "foobar.png";
var fileId2 = "barfoo";
var fileValue2= "barfoo.jpg";

// Create top-level image object
var images = {};

// Create second-level object in images object with
// the name of sectionName value
images[sectionName] = {};

// Create a third level object
var fileMapObj = {};

// Add the third level object to the second level object
images[sectionName][fileMap] = fileMapObj;

// Add forth level associate array key and value data
images[sectionName][fileMap][fileId] = fileValue;
images[sectionName][fileMap][fileId2] = fileValue2;


// All variables
alert ("Example 1 Value: " + images[sectionName][fileMap][fileId]);

// All keys with dots
alert ("Example 2 Value: " + images.TestSection.fileMapData.foobar);

// Mixed with a different final key
alert ("Example 3 Value: " + images[sectionName]['fileMapData'][fileId2]);

// Mixed brackets and dots...
alert ("Example 4 Value: " + images[sectionName]['fileMapData'].barfoo);

// This will FAIL! variable names must be in brackets!
alert ("Example 5 Value: " + images[sectionName]['fileMapData'].fileId2);
// Produces: "Example 5 Value: undefined".

// This will NOT work either. Values must be quoted in brackets.
alert ("Example 6 Value: " + images[sectionName][fileMapData].barfoo);
// Throws and exception and stops execution with error: fileMapData is not defined

// We never get here because of the uncaught exception above...
alert ("The End!");
</script>
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.