-1

I am having a hard time trying to accessing any elements in my object.

Find below my code that accesses the object from the localStorage and prints it out on the browser console:

var test = localStorage.getItem('transactionData');
console.log(test);

The above code yields:

[{Amount":"15,000","payersNumber":"070505788","waitersName":"Agnes"}]

When I try to access the element waitersName as seen in the code below:

console.log(">> " +test.waitersName);

It yields:

>> undefined

How do I access the various elements in my object?

SirBT
  • 1,580
  • 5
  • 22
  • 51

2 Answers2

2

test is an array with an object in it, you'll need to access the array item first with test[0] and that will return the object, which will then allow you to access its properties.

Miles Grover
  • 609
  • 3
  • 5
  • Thanks but if this is what you mean `console.log(">> " +test[0].waitersName);` this yields: `>> undefined` – SirBT Jul 24 '19 at 21:07
1

The data you retrieve from localstorage is a stringified version of the Javascript array. You first have to parse it using

  var array = JSON.parse(test);

Then get your elements from the parsed array.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
Staphy
  • 19
  • 1
  • 5