-3
array = {
event: [{
        key: "value",
        lbl: "value"
    }],
event1: [{
        key: "value",
        lbl: "value"
    }]

var variable;
if(variable in array){
//what to do here?
}

I have a value in the variable which will be the name of the array inside the array (i.e):variable="event" or "event1"; i want a function to return the array with the key in the variable!!

1

3 Answers 3

1

You need to use [] Bracket notation to access object if you want to access any property using variable

let arr = {event: [{key: "value",lbl: "value"}],event1: [{key: "value",lbl: "value"}]}

var variable = 'event1'

console.log(arr[variable])

Sign up to request clarification or add additional context in comments.

Comments

0

Your array variable isn't an array, its an object. You can access an object's properties/values (ie: event and event1) using bracket notation:

arr["event1"] // returns the array (the key's value) at event one.

Thus, you can use the following arrow function to get any value from any given key from any given object:

getVal = (obj, key) => obj[key];

While a function isn't necessary, I have created one as per your request. Alternatively, you can just use:

obj[varaible] // returns the array (value) from the key (variable)

See working example below:

const obj = {
  event: [{
    key: "value",
    lbl: "value"
  }],
  event1: [{
    key: "value",
    lbl: "value"
  }]
},
getVal = (obj, key) => obj[key],

variable = "event";
console.log(getVal(obj, variable));

Comments

0

Use the bracket notation to access the key from the object

array = {
event: [{
        key: "value",
        lbl: "value"
    }],
event1: [{
        key: "value",
        lbl: "value"
    }]
}
var variable='event1';
console.log(variable, array[variable])

1 Comment

Missing explanation

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.