0

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

1 Answer 1

1

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,

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

  • Other way using || (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'));

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.