0

I have a very simple snipplet for a json array and a javascript function that now returns a single argument:

<!DOCTYPE html>
<html>
<body>

<h2>JSON Array Test</h2>

<p id="outputid"></p>

<script>
var arrayinput = '{"collection":[' +
'{"firstAttr":"XXXA","secAttr":"13156161","lastAttr":"01" },' +
'{"firstAttr":"XXXB","secAttr":"11153325","lastAttr":"02"  },' +
'{"firstAttr":"XXXC","secAttr":"14431513","lastAttr":"03"  },' +
'{"firstAttr":"XXXC","secAttr":"161714","lastAttr":"01"  },' +
'{"firstAttr":"XXXC","secAttr":"151415","lastAttr":"02"  },' +
'{"firstAttr":"XXXC","secAttr":"114516","lastAttr":"02"  },' +
'{"firstAttr":"XXXC","secAttr":"131417","lastAttr":"03"  },' +
'{"firstAttr":"XXXC","secAttr":"1311865","lastAttr":"03"  },' +
'{"firstAttr":"XXXC","secAttr":"1314153","lastAttr":"01"  },' +
'{"firstAttr":"XXXC","secAttr":"13312163","lastAttr":"01"  }]}';

obj = JSON.parse(arrayinput);
document.getElementById("outputid").innerHTML =
obj.collection[1].firstAttr + " " + obj.collection[1].secAttr;
</script>

</body>
</html>

Now the problem is that I don't want to return just one value but multiple ones. For example all entrys with lastAttr=01 should be returned.

Therefore I would need something along the line of:

for(var i in obj) {                    
    if(lastAttr[i]="01") {
        document.getElementById("outputid").innerHTML =
        obj.collection[i].firstAttr + " " + obj.collection[i].secAttr;
    } else {

    }
}

Any idea on how to make this work?

1
  • Just curious, why are you embedding a string of JSON in your code? Or is this just a representation for the example? Commented Jul 28, 2015 at 13:39

3 Answers 3

1

If you want to perform a where you need to use Array.prototype.filter:

var filteredArr = arr.collection.filter(function(item) {
   return item.lastAttr == "01";
});

And, finally, you can use Array.prototype.forEach to iterate results and perform some action:

var outputElement = document.getElementById("outputid");
filteredArr.forEach(function(item) {
    // Check that I used insertAdyacentHtml to be sure that all items
    // will be in the UI!
  outputElement.insertAdjacentHTML("afterbegin", item.firstAttr + " " + item.secAttr);
});

Also, you can do it fluently:

var arr = {
  collection: [{
    firstAttr: "hello",
    secAttr: "world",
    lastAttr: "01"
  }, {
    firstAttr: "hello 2",
    secAttr: "world 2",
    lastAttr: "01"
  }]
};

var outputElement = document.getElementById("outputid");
var filteredArr = arr.collection.filter(function(item) {
  return item.lastAttr == "01";
}).forEach(function(item) {
  outputElement.insertAdjacentHTML("afterbegin", item.firstAttr + " " + item.secAttr);
});
<div id="outputid"></div>

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

6 Comments

Please don't tell people to use .innerHTML += .... It causes such huge problems. Use insertAdjacentHTML() instead.
@squint Well, I can change this.. I didn't tell "use it". I said "you need to concatenate at least"...
I get a blank screen with no error message on the two above snipplets.
For some reason it is not writing to the p-block. Both of your answers @squint and yours have that problem. Am I missing somehting here?
@Thevagabond I've added a runnable sample
|
1

You need to iterate over the collection Array and append the new stuff. Right now you're iterating the outer object and overwriting the .innerHTML each time.

var out = document.getElementById("outputid");

for (var i = 0; i < obj.collection.length; i++) {                    
    if(obj.collection[i].lastAttr=="01") {
        out.insertAdjacentHTML("beforeend", obj.collection[i].firstAttr + " " + obj.collection[i].secAttr);
    }
}

Note that I used == instead of = for the comparison, and .insertAdjacentHTML instead of .innerHTML.

2 Comments

I get "The content of elements must consist of well-formed character data or markup." as a error message.
The problem seems to be with the for loop. When deleting that I get a blank page, so it not writing to the p-block and the error is gone
0

if you want to replace html try this

(someCollection) array;
 var r = new Array();
    var j = -1;
    r[++j] = '<ul class="list-group">';
    for (var i in array) {
        var d = array[i];
        if (d.attribute== somevalue) {
            r[++j] = '<li class="list-group-item">'
            r[++j]=d.otherattribute;
            r[++j] = '</li>';
        }
    }
    r[++j] = '</ul>';
    //for(var b in r) //alert to see the entire html code
    //{ alert(r[b]);}
    firstLoadOnPage = false;
    var list = document.getElementById('SymptomSection');
    list.innerHTML = r.join('');

this replaces the inside of element with classname "SymptomSection"

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.