简体   繁体   English

根据给定值查找嵌套数组

[英]find nested array based on given value

var myarr = new Array([001,"Ravi",800000],[002,"John",700000],[003,"Vishal","500000"],
                      [004,"Michel",600000],[005,"Stella",700000]);

How to display one array from myarr ? 如何从myarr显示一个数组? For example if I enter 002 in input box it should display: 002,"John",700000 例如,如果我在输入框中输入002 ,则应显示: 002,"John",700000

I would recommend changing your data structure to something resembling a map. 我建议将您的数据结构更改为类似于地图的内容。 Then you can print out each person's data using the number (or string representation thereof) as a key. 然后,您可以使用数字(或字符串表示形式)作为键来打印每个人的数据。 Something like this: 像这样:

var data = {};
data["001"] = ["Ravi", 800000];
data["002"] = ["John", 700000];
data["003"] = ["Vishal", 500000];
data["004"] = ["Michel", 600000];
data["005"] = ["Stella", 700000];

var input = "002";
console.log(data[input]);

Demo here: 演示在这里:

Rextester 右旋酯

This is a classic example of Arrays inside an array. 这是数组内部数组的经典示例。

If you want to display the entire array 002,"John",700000 then take an index of that array from the outer array. 如果要显示整个数组002,“ John”,700000,则从外部数组获取该数组的索引。

eg 例如

<html>
<body>

<p id="demo"></p>

<script>
var myarr = new Array([001,"Ravi",800000],[002,"John",700000],[003,"Vishal","500000"],[004,"Michel",600000],[005,"Stella",700000]);

//This will display your entire second array.
document.getElementById("demo").innerHTML = myarr[1];

</script>

</body>
</html>

If you want a lookup to try key-value data structure in which your id will be key and the entire object will be value. 如果您要查找尝试键-值数据结构,其中您的id将是键,整个对象将是值。

eg var obj = {key1: value1, key2: value2}; 例如var obj = {key1:value1,key2:value2};

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

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