-1

I can't figure out what I'm doing wrong when accessing this JSON object:

{ Items: 
   [ { mId: 'who' },
     { mId: 'am' },
     { mId: 'I' } ],
  Count: 3,
  ScannedCount: 3 }
{ Items: 
   [ { cId: 'big' },
     { cId: 'scary' },
     { cId: 'muppet' } ],
  Count: 3,
  ScannedCount: 3 }

This is the object I am getting back from a function and I'm trying to access the individual items to update their values.

When I want to print 'who' for example, I do this:

console.log(obj.Items[0].mId)

Now I expect to get 'who' back, but this is what prints:

undefined
who

That 'undefined' always tags along. What am I doing wrong here?

Also, if I try to change the value somewhere by doing:

obj.Items[0].mId = 'x'

This happens:

{ Items: 
   [ { mId: 'x' },
     { mId: 'am' },
     { mId: 'I' } ],
  Count: 3,
  ScannedCount: 3 }
{ Items: 
   [ { cId: 'big', mId: 'x' },
     { cId: 'scary' },
     { cId: 'muppet' } ],
  Count: 3,
  ScannedCount: 3 }

This is not what I want.. I don't understand how to access only the first 'Items'. It seems like I'm accessing both.

Any help or advice is greatly appreciated. I probably don't need to say that I'm not very used to working with JSON.

stacked
  • 21
  • 2

1 Answers1

0

For the undefined issue, please see the answer here: What does it mean if console.log(4) outputs undefined in Chrome Console? but TL;DR you're just seeing the 'undefined' return from console.log(), because it has no return value. It shouldn't be an issue once you're not working in the console.

As for how you have 2 separate objects both called obj, I don't understand, as other said in the comments, please post the full code so we can see how this is being used/generated.

Also for clarification it looks like you're working with JavaScript objects, not JSON, similar but not the same.

Community
  • 1
  • 1
Caleb O'Leary
  • 753
  • 6
  • 10