-1

I seem to be having trouble accessing individual elements of a json array. Given this code:

json_array=JSON.parse(data);
console.log(json_array);
console.log(json_array.title);
console.log(json_array.requester);
console.log(json_array.none);

This is the output:

Array(3)
   0: {requester: false}
   1: {title: false}
   2: {none: true}
   length: 3
   [[Prototype]]: Array(0)
undefined
undefined
undefined

Obviously I am somehow accessing the individual elements incorrectly. What am I missing? TIA.

3
  • Your json array is an array and not an object, the problem is when you try to access directly a property, you should loop on the elements of your array and then access every property (json_array[0].title) Commented Aug 28, 2022 at 16:27
  • 1
    you are trying to access an array with dot notation which is how we access object properties,not array items Commented Aug 28, 2022 at 16:29
  • Does this answer your question? Accessing Object Property Values Within an Array - JavaScript Commented Aug 28, 2022 at 16:41

4 Answers 4

2

It seems like you forget the index when accessing array

console.log(json_array[0].title);
console.log(json_array[1].requester);
console.log(json_array[2].none);

Sign up to request clarification or add additional context in comments.

1 Comment

I didn't forget, I didn't know. Thanks.
0

You need to access json_array this way:

console.log(json_array);
console.log(json_array[0].title);
console.log(json_array[1].requester);
console.log(json_array[2].none);

This is because your json_array is an array with three objects, like this:

[ { "title": "" }, { "requester": "" }, "none": "" ]

Comments

0

An alternative solution would be to destructure your array into individual variables,which you can use accordingly :

const arr = [
  {title:"title"},
  {requester:"requester"},
  {none:"none"}
]

const [title,requester,none] = arr

console.log(title,requester,none)

Comments

-1

Please try this:

json_array = Object.assign([], json_array).reduce((a, b) 
=> Object.assign(a, b), {});
console.log(json_array);
console.log(json_array.title);
console.log(json_array.requester);
console.log(json_array.none);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.