-1

I want to dynamically fetch the value of an object. Here is the object:

myObj = {
person1:{name:"John Doe", age:"46"},
person2:{name:"Peter Deer", age:"36"},
person3:{name:"Ben Boar", age:"21"}
}

I have a function to fetch a desired name from the objects. Here's the function:

showPersonName(objKey: number) {
console.log(this.myObj + 'person' +objKey.name);
}

The result I want if I pass 1 as objKey is to display John Doe, but Visual Studio Code shows

Property 'name' does not exist on type 'number'.

Please, what can I do? I've had a hard time with this.

Benny64
  • 177
  • 3
  • 9
  • Provide complete code. Plunker would be helpful. – kind user May 01 '17 at 18:01
  • What is this number you are trying to pass referring to in your object? Meaning what is this object key 1?? There is no such key in your object. – AT82 May 01 '17 at 18:30

2 Answers2

0

You are defining

fetchMyObj(objKey: number) {

objKey is a number and how you can search for its name

Update 1:

showPersonName(objKey: number) {
    console.log(this.myObj.find(obj =>{ return obj.age:objKey}))
}

Object format

myObj = [{name:"John Doe", age:46},
         {name:"Peter Deer", age:36},
         {name:"Ben Boar", age:21}];

PLUNKER

Aravind
  • 40,391
  • 16
  • 91
  • 110
  • To fetch John Doe, it's as easy as console.log(this.myObj.person1.name); But I want to fetch it dynamically by being able to pass a number to my function so that I can get name from any person object. – Benny64 May 01 '17 at 18:01
  • please put me through cos I'm new to angular. – Benny64 May 01 '17 at 18:09
0

Oh my! My problem was improper usage of concatenation. I found help here: JavaScript object: access variable property by name as string I was supposed to use square brackets in my case.

console.log(this.myObj['person' + objKey].name);

That solved my problem. I'm grateful to you all, (especially @Aravind) for enduring my ignorance.

Community
  • 1
  • 1
Benny64
  • 177
  • 3
  • 9