简体   繁体   中英

Javascript Access Two-Dimensional Array

I have the following array

var array = [["ABC", "123"], ["DEF", "456"];

How can I get "123", if I look for "ABC? I tried

array["ABC"][1] //Want Output: 123
array["DEF"][1] //Want Output: 456

You can use Array#find .

 var array = [["ABC", "123"], ["DEF", "456"]]; let abc = array.find(x=>x[0]==="ABC"); console.log(abc?.[1]); let def = array.find(x=>x[0]==="DEF"); console.log(def?.[1]); let nothing = array.find(x=>x[0]==="NOTHING"); console.log(nothing?.[1]);

However, using an object or Map is much better suited to this purpose. You can convert your array to an object using Object.fromEntries .

 var array = [["ABC", "123"], ["DEF", "456"]]; const obj = Object.fromEntries(array); console.log(obj.ABC); console.log(obj['DEF']);

You can pass the array to the Map constructor as well. Map s are better if you always want to retain insertion order.

 var array = [["ABC", "123"], ["DEF", "456"]]; const map = new Map(array); console.log(map.get("ABC")); console.log(map.get("DEF"));

You can use find to locate the item with the value at index 0 . If you found, return the value at index 1 .

 const findByFirstValue = (arr, val) => ((res) => res? res[1]: null)(arr.find(v => v[0] === val)) console.log(findByFirstValue([["ABC", "123"], ["DEF", "456"]], 'ABC'))
 .as-console-wrapper { top: 0; max-height: 100%;important; }

You can use map

 const array = [["ABC", "123"], ["DEF", "456"]]; const newMap = new Map(); array.map(item=>{ newMap[item[0]] = item; }) console.log(newMap['ABC'][1]);

what you are trying to do is impossible using array, you are not allowed to use:

array["ABC"]

since array's indexing is number based, you need to use objects in order to get what you want:

var array = {"ABC": ["123", "789"], "DEF": ["456", "323"]};

now you are able to select them as you want:

array['ABC'][1] // 123

you can use index to get a value from array in

//first level
// array[0] =>["ABC", "123"]
// array[1] => ["DEF", "456"]

//second level 
// array[0][0]=> "ABC"
// array[0][1]=>  "123"

also you can use methods like map or foreach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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