0

For the sake of keeping this question limited, here is an example from W3Schools that I extended to give an idea of what I am trying to accomplish.

HTML:

<p id="demo"></p>

JS

var objA = [
    { "name":"John", "age":30, "city":"New York"},
    { "name2":"John2", "age2":302, "city2":"New York2"}
];

document.getElementById("demo").innerHTML = objA.name;

This prints undefined. What am I doing wrong?

Thanks!

After review... I have this now...

<p id="demo"></p>
<p id="demo2"></p>

for(var i=0;i < objA.length;i++){
    document.getElementById("demo").innerHTML += objA[i]["name"];
    document.getElementById("demo2").innerHTML += objA[i]["name"];
}

if I leave the =+ in, it prints both JohnJohn2 in both p tags. If I remove the +, it prints just John2 in both tags. The first p tag should print john, and the second should print john2

https://jsfiddle.net/gs4zdupn/

1
  • Try like this objA[0].name Commented Jun 6, 2018 at 13:04

4 Answers 4

2

Instead of

objA.name

You do

objA[0][“name”]
Sign up to request clarification or add additional context in comments.

1 Comment

what is i have multiple without knowing what index im on? how is a loop done in js?
1

For loop is like so

for(var i=0;i < objA.length;I++){
//whatever you want like objA[i]
}

1 Comment

thanks. cant add comment? its not adding both into demo. if I do += it adds both, but not in the way Im looking for. Im bascially taking a response and fulling in a bootstrap table.
0

The comment is a placeholder for your code. Don’t take it literally.

Comments

0

First let’s start from the beginning. Your JSON is in an array. So you don’t need name and name2. Just name it “name” for both.

var objA = [
{ "name":"John", "age":30, "city":"New York"},
{ "name":"John2", "age":302, "city":"New York2"}
];

Then for your for loop do this

for(var i=0;i < objA.length;i++){
document.getElementById("demo"+(i+1) ).innerHTML += objA[i]["name"];
document.getElementById("demo"+(i+1)).innerHTML += objA[i]["name"];
}

Remember to rename your p tag id’s as such

<p id="demo1"></p>
<p id="demo2"></p>

1 Comment

this didnt work. look at my jsfiddle... play around with it if u want.

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.