-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!!

Aswin Kumar
  • 73
  • 2
  • 10
  • 3
    Possible duplicate of [Add a property to a JavaScript object using a variable as the name?](https://stackoverflow.com/questions/695050/add-a-property-to-a-javascript-object-using-a-variable-as-the-name) and [How to create an object property from a variable value in JavaScript?](https://stackoverflow.com/questions/2241875) and [Get javascript object property via key name in variable](https://stackoverflow.com/questions/8556673) – adiga Feb 04 '19 at 05:35

3 Answers3

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])
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
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])
ellipsis
  • 12,049
  • 2
  • 17
  • 33
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));
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64