Reputation: 30
I have a json from API
let a = [{"name": 'abc',"age": '23'},{"name": 'qwe',"age": '37'},{"name": 'wqewqe',"age": '27'}]
then I want to create a function to be called
public testing(data, variable){
console.log('Second name : ', data[1].variable)
}
if i called
this.testing(a,'name');
the result should be
Second name : qwe
can anyone share to me how to do it?
Thank you
Upvotes: 0
Views: 641
Reputation: 5999
In general to we have two ways to access a property of an object as shown below
someObject.prop
someObject['prop']
So, here when you want to access a property of an object by using a variable we can achieve this using bracket notation i.e., obj[<variable>]
is the way.
Below is the example for the same.
let a = [{"name": 'abc',"age": '23'},{"name": 'qwe',"age": '37'},{"name": 'wqewqe',"age": '27'}];
//Provided an option to pass index as well
const printPropValue = (data, index, variable) => data[index][variable];
console.log(printPropValue(a, 1, 'name'));
console.log(printPropValue(a, 0, 'age'));
//console.log(printPropValue(a, 4, 'name')); --> Will crash
In the above approach there are some corner scenarios that need to be handled such as if the object at that index
could be null
or undefined
. There are multiple ways in order to tackle such scenarios,
Optional Chaining
let a = [{"name": 'abc',"age": '23'},{"name": 'qwe',"age": '37'},{"name": 'wqewqe',"age": '27'}];
//Provided an option to pass index as well
const printPropValue = (data, index, variable) => data[index]?.[variable];
console.log(printPropValue(a, 1, 'name'));
console.log(printPropValue(a, 0, 'age'));
console.log(printPropValue(a, 4, 'name'));
|| (OR operator)
let a = [{"name": 'abc',"age": '23'},{"name": 'qwe',"age": '37'},{"name": 'wqewqe',"age": '27'}];
//Provided an option to pass index as well
const printPropValue = (data, index, variable) => (data[index] || {})[variable];
console.log(printPropValue(a, 1, 'name'));
console.log(printPropValue(a, 0, 'age'));
console.log(printPropValue(a, 4, 'name'));
Upvotes: 1