Home > OS >  Better alternative to finding a value in array of arrays instead of using indices? (JavaScript)
Better alternative to finding a value in array of arrays instead of using indices? (JavaScript)

Time:12-12

I have JavaScript data that looks like this:

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

The second values in each array (bob, smith, 123 main st) are entered from the user. 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? 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"). Is there someway to do that with arrays?

Thanks!

CodePudding user response:

this way...
you may learn about Object.fromEntries()

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

CodePudding user response:

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);

  • Related