Sha
Sha

Reputation: 1974

Retrieving the value of array which is returned as string

I have the following array stored at the front end.

myArr[0] = new Array("AF", "B", "C", "D", "EM", "F", "G", "H", "I", "J");
myArr[1] = new Array("C", "DD", "M", "ED", "F", "DG", "B", "C", "D", "C");
myArr[2] = new Array("F", "G", "H", "I", "E", "F", "G", "H", "I", "J");

i need to get the value of the elements in an array. for example myArr[0][0] should return AF. unfortunately i am getting the position to be find of the array as string of array as follows from a service call.

["myArr[1][6]", "myArr[3][4]", "myArr[4][2]"]

how do i convert this and get the value at the array positions mentioned above. Thanks in advance.

Upvotes: 1

Views: 117

Answers (4)

Kobe
Kobe

Reputation: 6446

There's no need to over-complicate the issue. A simple map over each value and evaluate will suffice:

const myArr = [
  ["AF", "B", "C", "D", "EM", "F", "G", "H", "I", "J"],
  ["C", "DD", "M", "ED", "F", "DG", "B", "C", "D", "C"],
  ["F", "G", "H", "I", "E", "F", "G", "H", "I", "J"]
]

var positions = ["myArr[1][6]", "myArr[2][4]", "myArr[0][2]"]

positions = positions.map(eval)

console.log(positions)

Note, we can use the shorthand .map(eval) over .map(e => eval(e)) because we are only passing one element to one function, so the shorthand will do that for us.

Also, as Will pointed out, eval can be dangerous, as eval can execute malicious scripts.

Upvotes: 1

Ajanyan Pradeep
Ajanyan Pradeep

Reputation: 1132

This code will replace the positions stored in the array with their respective values.

let myArr=[]
myArr[0] = new Array("AF", "B", "C", "D", "EM", "F", "G", "H", "I", "J");
myArr[1] = new Array("C", "DD", "M", "ED", "F", "DG", "B", "C", "D", "C");
myArr[2] = new Array("F", "G", "H", "I", "E", "F", "G", "H", "I", "J");
let values=["myArr[1][6]", "myArr[2][4]", "myArr[0][2]"];
for (var i = 0; i < values.length; i++)
{
	 values[i]=eval(values[i])
}
console.log(values)

Upvotes: 0

Will Jenkins
Will Jenkins

Reputation: 9787

You can use eval to execute strings as script:

eval("myArr[1][6]") // gives "C"

See codepen here: https://codepen.io/jenko3000/pen/NZJRYK

Be careful though, executing strings as scripts is dangerous.

Upvotes: 3

Nick Parsons
Nick Parsons

Reputation: 50749

You can use regex to "extract" the two indices and then use them to get the values like so:

let myArr = [];
myArr[0] = new Array("AF", "B", "C", "D", "EM", "F", "G", "H", "I", "J");
myArr[1] = new Array("C", "DD", "M", "ED", "F", "DG", "B", "C", "D", "C");
myArr[2] = new Array("F", "G", "H", "I", "E", "F", "G", "H", "I", "J");

let arr = ["myArr[1][6]", "myArr[2][4]", "myArr[0][2]"];

let res = arr.map(str => {
  let [x, y] = str.match(/(\d+)/g);
  return myArr[x][y];
});
console.log(res);

Upvotes: 1

Related Questions