Get first property key of JSON for a TreeView - javascript

Thanks for the answers on the previous two questions. I have a new one, and this one is a collapsible panel in jQuery. The concept is, the first key of a JSON object will appear as a button, and the other keys will be treated as regular text like <p> and the like.
I have this function which tests for the first index of an object.
function isFirstIndex(obj){
var key;
for(key in obj){
if(obj[key]===0){
return true;
}
}
return false;
}
I have tried this one:
function generateTree(data, selId){
var cnt = "";
for (var i=0; i<5; i++){
var row = data[i];
$.each(row, function(key,value){
if (isFirstIndex(row)){
cnt += "<button>" + value + "</button><br/>";
} else{
cnt += "<strong>" + key + "</strong> :" + value + "<br/>";
}
});
cnt += "<br/>";
}
$(selId).html(cnt);
}
But eventually found out in debugging that the key in the isFirstIndex function is compared with a string.
Suppose I have a JSON :
{"userId" : 1, "name" : "cool name"}
I want to show the first key of any JSON set as a button, and the following properties will be ordinary text. Please allow me to post a pseudo-code like process.
Loop through all elements of data response
Loop through each key and value of each data element.
If the key is the first occurrence within the data set
display it as a button.
else
display it as ordinary text.
End Inner Loop
End outer loop

What UtsavShah means is that for (key in obj) may iterate keys in obj in any order, JS spec does not enforce any order.
In fact, JS spec does not enforce any order not only for iteration, but also for internal storage: each JS engine implementation (hence depending on browsers) may store your JSON keys in any order, so even though you write your "userId" first, it does not mean at all that the browser will keep it as the first key. For that, you have to use an Array, or use a convention with a specific key.
The way your code is written, it will look for a key named "0" in your object (row). BTW your i iterator is useless in isFirstIndex function.
What you may try to achieve is to test if the value assigned to "userId" key is equal to 0? In that case, you would simply test if (obj["userId"] === 0).
EDIT: (after you have explained that userId is the one to be a button)
If you just want the value in key "userId" to be displayed as a button, you would simply do:
function generateTree(data, selId){
var cnt = "";
for (var i=0; i<5; i++){
var row = data[i];
$.each(row, function (key,value) { // Note that $.each does not necessarily iterates in any specific order either.
if (key === "userId"){
cnt += "<button>" + value + "</button><br/>";
} else{
cnt += "<strong>" + key + "</strong> :" + value + "<br/>";
}
});
cnt += "<br/>";
}
$(selId).html(cnt);
}
EDIT2:
If you want an order, you need an array. If you want ordered keys, you could shape your data like so (of course this must be implemented in both server and client):
[
{"userId": 1},
{"name": "cool name"}
]
If you just need to know which particular key is specific and should be set as a button, make up a convention with your server and have your data specify which is the specific key, e.g.:
{
"userId": 1,
"name": "cool name",
"specificKeyToBeTransformedIntoAButton": "userId"
}

Related

Split json data using comma

I have a json which has a key "tag", which is returning data like this
"tags": "jname,gender,city"
but i want to append these value in separate span like below
<div class="info">
<span>jname</span><span>gender</span><span>city</span>
</div>
I am trying with this
$.getJSON("data.json", function(tagsposts) {
var items = [];
splitsVal = tag.split(",");
for (var i = 0; i < splitsVal.length; i++) {
obj.push({name:splitsVal[i]});
obj[i] = '<span>' + obj[i] + '</span>';
$('.tags-div').append(obj[i])
}
$.each(tagsposts, function(key, val) {
items.push('' + val['tags'] + '');
});
$('#tagsposts').append(items.join(""));
});
Am I doing correct
You're trying to split an undefined variable:
function(tagsposts) {
var items = [];
splitsVal = tag.split(","); // but tag doesn't exist...
(If you look at your browser console, which you should get into the habit of doing, you'll get a very clear message about why this isn't working: "ReferenceError: Can't find variable: tag".)
Since you haven't provided your JSON it's not possible to say exactly how to fix this. Assuming the full JSON is of the form
{"tag": "foo,bar,baz"}
then you would want
splitsVal = tagsposts.tag.split(",")
If there's more structure than that inside the JSON, you'll need to crawl down through that parsed object to find the "tag" value(s) you need.
There are lots of other problems here, however.
You also try to push onto an undefined array named obj; you'd need at least a var obj = [] outside that for loop. Though it's not clear why you're using obj at all, or trying to draw an object {name: val} into the DOM instead of just the value. What you're trying to do is just read splitsVal[i] so you can just do this:
for (var i = 0; i < splitsVal.length; i++) {
$('.tags-div').append('<span>'+splitsVal[i]+'</span>')
}
And you try to iterate over tagsposts as if it's an array when generating the #tagsposts contents. (Is your JSON an array? If so you need to iterate over it when getting the tag values too.)

get values from json variable data with jquery or javascript

The json output is some thing like:
{"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1}
I need to do an append with each of the received values. The numbers next to them are how many times they exist.
I know it will probably be something with "for each" value, but, since the values and keys of the json response are variable, it's difficult for me how to figure out the way to do it.
I will like that the append order depends on how big the number is. If it's bigger print it on the top, and so on...
for example:
<div id="values">
<p>The value "more" is repeated 5 time(s).</p>
<p>The value "apple" is repeated 3 time(s).</p>
<p>The value "another" is repeated 1 time(s).</p>
...
</div>
Remember! The response can change, the response won't be always apple, another, more, volvo, audi and ford... It can CHANGE!
EDIT:
I can do something with this, but, how do I order them with higher or lower values?
for (var key in interests) {
if (interests.hasOwnProperty(key)) {
console.log(key + " -> " + interests[key]);
}
}
EDIT:
var data = {"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1}; // initial data
var interestsValue = []; // data with values
for (var key in data){ interestsValue.push({ name: key, value: data[key] }); } // send data with values
interestsValue.sort(function(a, b){ return b.value - a.value; }); // sort values
console.log(interestsValue); // values ordered from bigger to smaller
First - convert the object to a valid array:
var data = {"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1};
var arr = [];
for (var key in data)
{
arr.push({ name: key, value: data[key] });
}
Then.... use that array with jQuery, angular, etc... to populate your elements
Enjoy :)
Like this.Loop through your objcet using jquery's $.each method Then append the html into your div with append method.
var obj= {"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1};
text = "";
$.each(obj,function(index,element){
text +=" <p>The value " +index+ " is repeated "+ element + " time(s).</p>";
});
$("#values").append(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="values">
</div>
JS fiddle https://jsfiddle.net/uobedcf0/
See UPDATED Fiddle:
https://jsfiddle.net/u1kn6d6L/1/
As mention above first convert object into the array.
var data = {"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1};
function sortByValue (data){
var dataArray=[];
for(var key in data){
dataArray.push({name:key ,value :data[key]});
}
dataArray.sort(function(a,b){return b.value- a.value}); //sort it in descreasing order
return dataArray;
}
var text="";
var objArray = sortByValue(data);
$.each(objArray,function(index,object){
text +=" <p>The value " +object.name+ " is repeated "+ object.value + " time(s).</p>";
});
$("#values").append(text)

Remove an object from an array on a condition

I have a csv file that I've already splitted by line breaks and I've broken it down even more by the commas in the line breaks to give me three things I'm looking for and named them for later use in the program. What I'm looking to do is remove an item if a one of the objects match a certain value.
var values=[];
var output="";
for(i = 0; i < csv_split.length; i++){
csv_split[i] = csv_split[i].split(',') //Splits the csv file that's already split by new line by commas
values[i]={}
values[i].Name=newline_split[i][1]; //finds the second object and names it values.name
values[i].Rev=newline_split[i][2]; //finds the third object and names it values.rev
values[i].URL=newline_split[i][9]; //finds the eighth object and names it values.url
}
This then is used later so I can get a list of just the values I'm looking for.
for (i=0; i < values.length; i++){
output += values[i].Name + ',';
output += values[i].Rev + ',';
output += values[i].URL+ ',';
output += "\n\n||||||";
}
So what I did was modified this code to the first for loop:
if (values[i].Rev == "NO ACCESS") {
csv_split[i].splice(0,1);
}
The idea behind this was that if the values.Rev matched to "NO ACCESS" it would remove the entirety csv_split[i], so that later it wouldn't display it in the output.
Running the script now gives the entire output of regardless if values.Rev matches "NO ACCESS" or not. What am I missing with this?
You could do this much easier with the filter method. You use it like this:
var finalArr = values.filter(function(val) { return val.Rev != "NO ACCESS"; });
This should give you an array of everything that has access.

How to loop data in javascript

I have an object like these
var itemlist= {"50271":2,"50025":1,"90012":3}1
It indicates the reagent to include in a mixture. The property name is the ID of the reagent and the property value the quantity. I would like to generate HTML to display the reagents of a mixture as follows
<img src='50271.jpg'> x 2
<img src='50025.jpg'> x 1
<img src='90012.jpg'> x 3
How can I loop the object to get my expected output?
You can loop over the properties of an object using the for (prop in obj) syntax and generate your specific HTML like this:
var itemlist = {"50271":2,"50025":1,"90012":3};
var html = "";
for (var prop in itemList) {
html += "<img src='" + prop + ".jpg'> x " + itemList[prop];
}
// insert the html somewhere now
P.S. I would guess you may want a <br> after each line.
P.P.S. Data in a javascript object has no guaranteed order so the iteration could end up in any order. You have to use an array if you want a collection in a particular order or you can collect all the keys of the object first and then sort the keys before using them.
You'll want to loop through the object like this
for (var key in itemlist) {
if (itemlist.hasOwnProperty(key)) {
alert(key + " -> " + itemlist[key]);
}
}
As shown here:
How do I loop through or enumerate a JavaScript object?

Log input into array, print only new input

Okay I have a a couple of functions. I don't think most of them are relevant. What I want to do is create an html list when you click a button, and store the value in an array. However I want to be able to update this list without outputting the entire array again. I have it set up to accept the input and I can get it to loop and print the array but it will print the entire array and I only want one. This seems like a common thing but my Google-fu returned nothing.
So I have a list variable that connects to an input, logs it into an array, and another function to clear it and print out the values.
Code snippet:
var listItemInput= document.getElementByID("listItem");
var listItem= [];
function insertListItem(){
listItem.push(listItemInput.value);
clearAndShow();
}
function clearAndShow(){
listItemInput.value= "";
}
function printList{
for (var i = 0; i < listItem.length; i++){
document.getElementById("list").innerHTML += '<li>' + listItem[i] + '</li>';
}
When the printList funciton is called by pressing the button it prints the entire array over however I would like a button that simply prints the newest item. How could I do that?
For clarification, I need to print out the list to html and store the values in an array, the values will later be referenced in an if else argument to combine and print them with new variables.
EDIT:
I plugged in the var = lastIndex and changed it as well as made two more variables for my list. This seems to make it work. Thank you.
You could keep track of the last index printed.
var listItemInput= document.getElementByID("listItem");
var listItem = [];
var lastIndex = 0; //Keep track of the last index shown.
function insertListItem() {
listItem.push(listItemInput.value);
clearAndShow();
}
function clearAndShow() {
listItemInput.value = "";
}
function printList() {
for (; lastIndex < listItem.length; lastIndex++) {
document.getElementById("list").innerHTML += '<li>' + listItem[lastIndex] + '</li>';
}
}
This approach assumes you won't be removing items from listItem array, which you didn't express is something that would be done.
If you only want one element, why do you need to iterate?
function printList() {
document.getElementById('list').innerHTML = '<li>' + listItem[listItem.length-1] + '</li>';
}

Categories

Resources