-3

If this is a JS object, how can I access the values of apples and pinapples? I guess this is the key?

How can I reference the object to extract apples? Same question for accessing the subarray a and value at c.

Please explain how to access the key and values of this object.

{ apples: 
   { a: [ '51.01', '12', '123' ],
     c: '8888' },
  pinapples: 
   { a: [ '123', '6', '88' ],
     c: '333' },
}
Teemu
  • 22,918
  • 7
  • 53
  • 106
Kelvin U
  • 353
  • 4
  • 15
  • um... myObj.apples or myObj.apples.c or myObj.apples.a[2] learn about dot and bracket notation https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets – epascarello Sep 18 '17 at 16:54
  • Possible duplicate of [JavaScript property access: dot notation vs. brackets?](https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) – TheCog19 Sep 18 '17 at 17:01
  • But if I don't know that apples is the first object. How can I access the first object in the main object. I want to return "apples" – Kelvin U Sep 18 '17 at 20:31

1 Answers1

0

simply if you have json called anything like obj1 you can access to it is properties easily obj1.propery name for eaxmple:

bar obj1 = {
 a: 'test value 1',
 b: 'test value 2'
 }

you can access to a directly by typing obj1.a it will return "test value 1"

but if it was an other object contains other properties like this:

var obj2 = {
 a : {
        var1: 'var1 value',
        var2: 'var2 value'
        },
  b : {
        var1: 'var1 value',
        var2: 'var2 value'
        },
  c: 'c value'
  }

you can access to C -> obj2.c but what about A

you can access it by typing obj2.a it will return object but if you want access to it is preoperties you can write

obj2.a.propertyName // like obj2.a.var1 will return var1 value

and if it was array like your example you can access to your requested properties

myobj2.apples // will return apples as object
myobj2.apples.c // will return apples.c as normal string
myobj2.apples.a // will return apples as array
myobj2.apples.a [0] // will return apples as array index number 0
myobj2.apples.a [1] // will return apples as array index number 1

I hope I helped you

see also

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics

Mohammed Ahmed
  • 423
  • 4
  • 15