2

I have the following JSON Array data from which I want to print Charlie. How to do it?

[ [ {
"ID": 1,
"Name" :"David"
},{
"ID": 2,
"Name" :"Antony"
}],[{
"ID": 1,
"Name" :"Bob"
},{
"ID": 2,
"Name" :"Charlie"
} ] ]
5
  • what error does it gives, how are you printing ?? can you post how you are printing ? Commented Feb 19, 2020 at 10:28
  • {PostData.map((group, index)=>{ return <p>{group.Name}</p> This prints all the names, but I want to print only the first or second name Commented Feb 19, 2020 at 10:30
  • If you are reading this array asynchronous than this can be empty so first check if that has at least one item then try to access with data[0] Commented Feb 19, 2020 at 10:30
  • I have this array in json file. Commented Feb 19, 2020 at 10:31
  • If you only want the first one, then don't map the whole array. Just take the first element. Commented Feb 19, 2020 at 10:41

3 Answers 3

4

you are using {PostData.map((group, index)=>{ return <p>{group.Name}</p>, since you are using map here PostData[0].Name will throw error inside map(), because you are iterating array with map().

Since you only need first item, you can simply use <p>PostData[0].Name</p>

var data = [{
"ID": 1,
"Name" :"David",
},  {
"ID": 2,
"Name" :"Antony",
}];

console.log(data[0].Name)

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

8 Comments

This way, it printed the same name twice.
@AnmolKhanna are you using like this {PostData.map((group, index)=>{ return <p>{postData[0].Name}</p> } ??
Yes, exactly this way.
thats why its printing twice, dont use .map(), use like {PostData && <p>{PostData[0].Name}</p>}
PostData((group, index)=>{ return <p>{PostData[0].Name}</p> This gave an error
|
2
var response= [{
"ID": 1,
"Name" :"David",
},  {
"ID": 2,
"Name" :"Antony",
}];

console.log(response[0].Name) will give you first element of Array and return data with Key 'Name'.

Comments

0

I tried all of the above and although the console.log(data[0].Name) would work to test the value, when it came to inserting the chosen value within the returned html code, I needed to use the code below. The reason is when we return the rows of data, only one row is valid and we need to use the "?" condition, as explained here https://stackoverflow.com/a/62824031/7496293 to exclude all the other cases and not have your code break:

{data[0]?.Name}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.