get values from json variable data with jquery or javascript - 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)

Related

Searching For Existing Values in Array

I have been trying to search for an existing value in an array like below
var values = []
values.push(localStorage.getItem('items'));
console.log(values);
if (values.includes(2)) {
alert('Already Exists.');
}
When i console the array values i have output as ["1,2,3,4,5,6"] so the code treats the array as having just one index which is index[0] which makes the search quite challenging for me.
My challenge is how to find the value 2 in the array values ?
localStorage can only hold strings. As such you need to convert the value you retrieve in to an array, which can be done using split().
Also note that the resulting array will contain string values, so you need to use includes('2'). Try this:
var values = "1,2,3".split(','); // just for this demo
//var values = localStorage.getItem('items').split(',');
console.log(values);
if (values.includes("2")) {
console.log('Already Exists.');
}
Hope this help you.
var names_arr = '["1,2,3,4,5,6"]';
names_arr = names_arr.replace("'",'');
function checkValue(value,arr){
var status = 'Not exist';
for(var i=0; i<arr.length; i++){
var name = arr[i];
if(name == value){
status = 'Exist';
break;
}
}
return status;
}
console.log('status : ' + checkValue('3', names_arr) );
console.log('status : ' + checkValue('10', names_arr) );
First of all, this isn't jQuery, it's vanilla JS.
Second, after doing localStorage.setItem("items", [1,2,3,4,5,6]);, items in local storage will equal to "1,2,3,4,5,6", which is no longer the appropriate format.
Rather, save your array with localStorage.setItem("items", JSON.stringify([1,2,3,4,5,6]));. When you want to retrieve those items, write let vals = JSON.parse(localStorage.getItem("items"));, and search in vals with
vals.includes(2) for a true/false answer,
vals.find(val => val === 2) for 2 or undefined,
val.indexOf(2) to get the index of the
first element equal to 2.
Hope this helps.
firstly get the values from local storage store it in a variable, split it using the split
function, then check if the number is inside the array, alert the message if it returns true
var values =localStorage.getItem('items')
var spliter = values.split(',')
console.log(spliter);
if (spliter.includes('2') == true) {
alert('Already Exists.');
}

Get first property key of JSON for a TreeView

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"
}

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?

Compare HTML element with JSON array and replace

So I've been trying this for a while but no luck so far. What I want to achieve is, after selecting a value from the drop down, that value should be compared with the json multi-dimensional array. If it matches, then there are certain html elements on the webpage whose content needs to be replaced with the corresponding json values.
Here is the what I've been working so far (link)
<select onchange="executeMe(this)" id="selectOpt">
<option value="445">Choose...</option>
<option value="445">Daisy</option>
<option value="446">Romeo</option>
</select>
<br/><br/><br/>
<label id="entity_id">replaceThis</label>
So in the fiddle, if the user chooses "Daisy" from the dropdown, (the first array has Daisy in it) the corresponding value set from the array should be displayed in each of the html element on the webpage.
I can use only javascript for this. Thanks in advance guys...
You've got problems. First, your string you get back from your map function is massive and certainly won't pass an equality check with your option value. Additionally, your anonymous function is going to return the first value and not iterate through your for loop properly. There's no correlation between your select option values/labels and the items in the array. Try this:
function executeMe(select) {
var myselect = document.getElementById("selectOpt");
var selectOption = myselect.options[myselect.selectedIndex].innerHTML;
var i = theArray.length, obj, index, val;
while (i--) {
obj = theArray[i];
for (index in obj) {
val = obj[index];
//following matches on both keys and values, if you only
//want values delete the second part of the check
if (val == selectOption || index == selectOption) {
var string = '', prop;
for (prop in obj) {
string += prop + ': ' + obj[prop].toString() + '<br>';
}
document.getElementById('entity_id').innerHTML = string;
}
}
}
}
If this isn't what you need let me know with a comment.

getting comma before first element in an array in jquery

I am inserting some data into an array but I am getting
,9,My firstname,My lastname,myemail#example.com,123456789
out in my console. How can I remove comma from first element i.e. 9? here is my code
var data = new Array();
$(row_el.children("td")).each(function(i) {
var td = $(this);
//var data = td.html();
var td_el = td.attr('class');
//arr[i] = data;
if(!td.hasClass("element")) {
data[i] = td.html();
console.log(i + ": " + data);
}
});
I want output like this
9,My firstname,My lastname,myemail#example.com,123456789
then I will pass this array to a function and loop through this array.
Just use push() (MDN docu) instead of setting to a specific position inside your array:
var data = new Array();
$(row_el.children("td")).each(function(i) {
var td = $(this);
//var data = td.html();
var td_el = td.attr('class');
//arr[i] = data;
if(!td.hasClass("element")) {
data.push( td.html() );
console.log(i + ": " + data);
}
});
The problem is, that not all the elements in the array processed by each() result in an entry in your array. However, the index submitted to your callback (i) counts upwards nonetheless. So if there are some elements, that do not result in an entry to your array, these positions are filled with undefined (as long as you enter an element at a later position). These undefined entries now result in an empty string when outputting it the way you do, thus resulting to your leading comma.

Categories

Resources