-1

Lets say I have the following...

Example code:

const array = [{
  key1: {
    keyA: 'hello world',
    keyB: 'hello world'
  },
  'key2 with space': {
    keyA: 'hello world',
    keyB: 'hello world'
  },
  key3: {
    keyA: 'hello world',
    keyB: 'hello world'
  }
}]

How would I console log the 'key2 with space' value's object as shown in the code above.

I tried the following console.log(array[0].['key with space']). But this results in a syntax error that isn't very will defined.

Fiddle Freak
  • 1,923
  • 5
  • 43
  • 83
  • 2
    You can remove dot (.) and try array[0]['key with space'] – Nitish Narang Nov 20 '18 at 05:36
  • @user202729 I did, sorry I will edit it – Fiddle Freak Nov 20 '18 at 05:37
  • 1
    Possible duplicate of [access javascript object with space in key](https://stackoverflow.com/questions/8317982/access-javascript-object-with-space-in-key) – Jeto Nov 20 '18 at 05:37
  • @Jeto I don't think it's a duplication of that question, because the question is a nested object not inside an array. And the parent array has a name. – Fiddle Freak Nov 20 '18 at 05:38
  • @FiddleFreak Well, the array access didn't seem to be the issue there, accessing that kind of key with spaces in it did. Anyway, you got your answer :) – Jeto Nov 20 '18 at 05:40
  • @Jeto Yes I know, but the main answer to that question was the solution I tried to do myself... which means it is slightly different. My question adds one more layer of abstraction (an array), which causes the parent object to be nameless (unlike the possible duplicate question. Good eye though ^^. Maybe I should have worded the question title better. – Fiddle Freak Nov 20 '18 at 05:42

1 Answers1

2

You can access object properties in two ways, one is using the dot (.) operator and the other is using the square bracket ([]). You are using both. Since the key contains space, you have to use the bracket notation. Also, the key name you are trying in console does not match ('key2 with space' != 'key with space').

Remove dot:

const array = [{
  key1: {
    keyA: 'hello world',
    keyB: 'hello world'
  },
  'key2 with space': {
    keyA: 'hello world',
    keyB: 'hello world'
  },
  key3: {
    keyA: 'hello world',
    keyB: 'hello world'
  }
}]
console.log(array[0]['key2 with space'])
Mamun
  • 66,969
  • 9
  • 47
  • 59