Creating a 2d associative array javascript (same as a php assoc array)

穿精又带淫゛_ 提交于 2019-12-02 04:54:06

JavaScript doesn't have associative arrays. It has (numeric) arrays and objects.

What you want is a mix of both. Something like this:

var infArray = [{
    name: 'Test',
    hash: 'abc'
}, {
    name: 'something',
    hash: 'xyz'
}];

Then you can access it like you show:

var name = infArray[0]['name']; // 'test'

or using dot notation:

var name = infArray[0].name; // 'test'

simply var infArray = [{name: 'John'}, {name: 'Greg'}] ;-)

JavaScript doesn't have assoc arrays. Anything to any object declared as obj['somthing'] is equal to obj.something - and it is a property. Moreover in arrays it can be a bit misleading, so any added property won't changed array set try obj.length.

JavaScript do not have 2D associative array as such. But 2d associative array can be realized through below code:

var myArr = { K1: {
    K11: 'K11 val',
    K12: 'K12 Val'
    },
    K2: {
    K21: 'K21 Val',
    K22: 'K22 Val'
    }
};
alert(myArr['K1']['K11']);
alert(myArr['K1']['K12']);
alert(myArr['K2']['K21']);
alert(myArr['K2']['K22']);  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!