-2

I am working on an API which consists of nested objects with numeric keys. Here is the data:

{ "data": {"0":{"name":"kp"},"1":{"name":"josan"}}

I am wondering how can a key be numeric. As per my knowledge it should not possible.

axios.get(``)
.then( res => {const persons = res.data;
    this.setState({persons});

 render(){return ({this.state.persons.data."1".name})

I want to access name of 1.

Jack Bashford
  • 40,575
  • 10
  • 44
  • 74

3 Answers3

2

Use bracket notation like so:

this.state.persons.data["1"].name

You can't use numbers usually because all JavaScript object keys are strings - and it gives you a syntax error if you try to use a number in dot notation:

const obj = { 1: "foo" };

console.log(obj..1);

However, because of a quirk of implicit conversion, numbers in bracket notation works fine:

const obj = { 1: "foo" };

console.log(obj[1]);
Jack Bashford
  • 40,575
  • 10
  • 44
  • 74
  • getting the same error TypeError: Cannot read property '1' of undefined – Kanwar Pal Singh Aug 07 '19 at 10:11
  • Uhh...where? The solution I have posted works - make sure you're copying it correctly. – Jack Bashford Aug 07 '19 at 10:12
  • That means that `this.state.persons.data` is undefined. Make sure it's defined, otherwise the code won't work. – Jack Bashford Aug 07 '19 at 10:13
  • Jack, there is a default "data" term which we used while getting response i.e res.data and i have a key of the same name as well "data".so basically what in was trying to access is this.state.res.data.data["1"].name P.S : i have already assigned res.data to persons. – Kanwar Pal Singh Aug 07 '19 at 10:56
  • I mean would react be able to differentiate between two "data". I am a having a tough time understanding this. – Kanwar Pal Singh Aug 07 '19 at 10:58
0

You can use [] (bracket) notation

var a={ "data": {"0":{"name":"kp"},"1":{"name":"josan"}}}
console.log(a.data[0].name)
console.log(a.data[1].name)
ellipsis
  • 11,688
  • 2
  • 14
  • 33
0

If { "data": {"0":{"name":"kp"},"1":{"name":"josan"}} is the response from the API, and you are already doing this: const persons = res.data;

Then to get the name you need to use this.state.persons['1'].name.

Bimalendu
  • 51
  • 4