简体   繁体   English

在 arrays 数组中查找值而不是使用索引的更好选择? (JavaScript)

[英]Better alternative to finding a value in array of arrays instead of using indices? (JavaScript)

I have JavaScript data that looks like this:我有看起来像这样的 JavaScript 数据:

[
  ["firstName", "bob"],
  ["lastName", "smith"],
  ["address", "123 Main St]
]

The second values in each array (bob, smith, 123 main st) are entered from the user.每个数组 (bob, smith, 123 main st) 中的第二个值是由用户输入的。 I'm simply wanting to print the entered value.我只是想打印输入的值。 I know I can use indices (such as [0][1] to capture "bob") but is there a better way to do that?我知道我可以使用索引(例如 [0][1] 来捕获“bob”)但是有更好的方法吗? I know JavaScript objects have a.get() method where you can enter the key and have the value returned (such as.get("firstName") to return "bob").我知道 JavaScript 对象有一个 .get() 方法,您可以在其中输入密钥并返回值(例如 .get("firstName") 返回“bob”)。 Is there someway to do that with arrays?有没有办法用 arrays 做到这一点?

Thanks!谢谢!

this way...这边走...

 const dataArr2 = [ [ "firstName", "bob"], [ "lastName", "smith"], [ "address", "123 Main St"] ] let obj = Object.fromEntries( dataArr2 ) console.log( obj.firstName ) // bob console.log( obj.lastName ) // smith console.log( obj.address ) // 123 Main St

There are multiple ways to do so.有多种方法可以做到这一点。 Please check the below given examples.请检查以下给出的示例。

 const personArr = [ ["firstName", "bob"], ["lastName", "smith"], ["address", "123 Main St"], ]; console.log(new Map(personArr)); console.log(Object.fromEntries(personArr)); function toObject(arr = []) { return arr.reduce((acc, [key, value]) => { acc[key] = value; return acc; }, {}); } console.log(toObject(personArr)); const { firstName, lastName, address } = toObject(personArr); console.log(firstName, lastName, address);

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

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