How to print JSON String object as a dropdown in javascript - javascript

I am getting jsonString object in my ajax call.can any one tell me how to print this object as a dropdown .
[
{
"id" : 3272,
"name" : "a"
},
{
"id" : 3255,
"name" : "b"
},
{
"id"
: 3257,
"name" : "c"
},
{
"id" : 3253,
"name" : "d"
},
{
"id" : 3256,
"name" : "e"
}
]
That's my code:
<script>
$(document).ready(function() {
$("#customerDetails").change(function() {
var value = $('#customerDetails :selected').text();
$.ajax({
type: 'GET',
url: 'environments',
data: {
selectedcustomername: value
},
success: function(result) { //this result is my jsonstring object alert("success");
}
});
});
});
</script>

Let say myJson is
{
"myJson": [
{
"id": 3272,
"name": "a"
},
{
"id": 3255,
"name": "b"
},
{
"id": 3257,
"name": "c"
},
{
"id": 3253,
"name": "d"
},
{
"id": 3256,
"name": "e"
}
]
}
var options = eval(myJson);
Using jQuery to fill options
var length = options.length;
for(var j = 0; j < length; j++)
{
var newOption = $('<option/>');
newOption.attr('text', options[j].name);
newOption.attr('value', options[j].id);
$('#mySelect').append(newOption);
}
Also have a look here

var row=[{"id":3272,"name":"a"},{"id":3255,"name":"b"},{"id"
:3257,"name":"c"},{"id":3253,"name":"d"
},{"id":3256,"name":"e"}];
var select="<select id='x'>";
for(var i=0,l=row.length;i<l;i++){
var item=row[i];
select+="<option value='"+item.id+"'>"+item.name+"</option>";
}
select+="</select>";
document.write(select);

By using simple for loop you can read each value and make a select box
var v = { "myJson": [ { "id": 3272, "name": "a" }, { "id": 3255, "name": "b" }, { "id": 3257, "name": "c" }, { "id": 3253, "name": "d" }, { "id": 3256, "name": "e" } ] }
// in your ajax success block write this and v is your response return by ajax
var str ='<select>';
for(var i=0;i<v.myJson.length;i++){
str += '<option value="'+v.myJson[i].id+'">'+v.myJson[i].name+'</option>';
}
str +='</select>';
$("body").html(str)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<body></body>

Here's a working fiddle: https://jsfiddle.net/q1ekcf6z/
var returnData = [{"id":3272,"name":"a"},{"id":3255,"name":"b"},{"id"
:3257,"name":"c"},{"id":3253,"name":"d"
},{"id":3256,"name":"e"}];
var options = '';
returnData.forEach(function(data){
options+= getOption(data.name);
});
var fullDropdown = '<select>' + options + '</select>';
document.write(fullDropdown);
function getOption(textTo){
return '<option>' + textTo + '</option>';
}

Related

Function to build a line to retrieve data from json

I'm writing a function that takes arguments and add them to form a line to look for data in a JSON file. I've defined a variable for the readFileSync and the add to it the arguments of the function to look for the data.
var jf = require('jsonfile'),
file = 'logins.json',
i = 1;
var jsonData = jf.readFileSync(file);
function getJSONData() {
var n = 1;
var com = '';
do {
if (arguments[n] !== undefined) {
com += `['${arguments[n]}']`;
}
n++;
} while (n < arguments.length);
return com;
}
var h = getJSONData(i, 'operator', 'id');
console.log(jsonData[i] + h);
This is my JSON:
[
{
"operator": {
"id": "avalle",
"pass": "Aa123456",
"something": "idk",
"account": [
{
"type": "asd",
"idk": "asd"
},
{
"type": "asd",
"idk": "asd"
}
]
}
},
{
"operator": {
"id": "oleal",
"pass": "Aa123456",
"something": "idk",
"account": [
{
"type": "asd",
"idk": "asd"
},
{
"type": "asd",
"idk": "asd"
}
]
}
}
]
I should get a line of jsonData[i]['param1']['param2'] that locates the data in the file.
Instead i get undefined or [object Object]['operador']['id']
If you want a property to be returned from the function you can make this change:
function getJSONData(jsonData) {
var n = 1;
var result = jsonData;
do {
if (result[arguments[n]]) {
result = result[arguments[n]]
} else {
console.error(`Property ${arguments[n]} does not exist on obj:`, result)
}
n++;
} while (n < arguments.length);
return result;
}
var h = getJSONData(jsonData[i], 'operator', 'id');
Otherwise you return a string from getJSONData that looks like "[prop1][prop2]" and it will not retrieve a property by trying to concat Object + string

Postman JSON parse response body arrays inside arrays

I have this JSON Response from API call
[
{
"id": 20599,
"name": "Deliver",
"options": [
{
"id": 63775,
"name": "Item",
"dataType": "SelectMultiOption",
"required": false,
"options": [
{
"id": 426,
"name": "Towels"
},
{
"id": 427,
"name": "Toothbrush"
},
{
"id": 428,
"name": "Pillow"
}
]
}
]
}
]
I am using this code to get the id of the service "Deliver"
var data = JSON.parse(responseBody);
var loop_count = 0
for (count = 0; count < data.length; count++)
{
if (data[count].name == "Deliver")
{
var job_id = data[count].id;
postman.setEnvironmentVariable("service_id", job_id);
}
}
The questions are:
How can I get value from array "options", I need to get the "id":
63775 and store as "item_id" and the "name":"Item" as "item_name" postman variables.
Then I need to select the "options" nested in record
"Item" and select the option "name": "Toothbrush" and store in postman
variable "svc_optn_optn_name" and it's "id" stored in
"svc_optn_optn_id"
Here I am giving my own suggestion for your problem with few lines of code. I am not sure, how are you going to use these values. I also don't know if the outer options array will always have 1 item or more. I have just tried to satisfy your questions.
Please ask/comment, if you have more doubts or I am wrong.
I have created a function getAllPostmanDataFrom(obj) which takes object as parameter which is the value of data[count], gathers necessary info in other object postmanObj and returns it to the caller.
function getAllPostmanDataFrom(obj) {
const item_id = obj.options[0].id;
const item_name = obj.options[0].name;
const svc_optn_optn_name = obj.options[0].options[1].name;
const svc_optn_optn_id = obj.options[0].options[1].id;
const postmanObj = {item_id, item_name, svc_optn_optn_id, svc_optn_optn_name}; // Return object
return postmanObj;
}
var data = [
{
"id": 20599,
"name": "Deliver",
"options": [
{
"id": 63775,
"name": "Item",
"dataType": "SelectMultiOption",
"required": false,
"options": [
{
"id": 426,
"name": "Towels"
},
{
"id": 427,
"name": "Toothbrush"
},
{
"id": 428,
"name": "Pillow"
}
]
}
]
}
]
var count = 0;
var obj = data[count];
var postmanObj = getAllPostmanDataFrom(obj);
//var {item_id, item_name, svc_optn_optn_id} = postmanObj;
console. log(postmanObj)
/*
console.log(item_id);
console.log(item_name);
console.log(svc_optn_optn_id);
console.log(svc_optn_optn_name);
*/
Finally, you can use values contained in postmanObj as follows:.
postman.setEnvironmentVariable("item_id", postmanObj.item_id);
postman.setEnvironmentVariable("item_name", postmanObj.item_name);
And so on.
This is the solution
var data = JSON.parse(responseBody);
variable named as data
var loop_count = 0
for (count = 0; count < data.length; count++)
{
if (data[count].name == "Deliver")
{
var job_id = data[count].id;
postman.setEnvironmentVariable("service_id", job_id);
var job1_name = data[count].options[0].name;
postman.setEnvironmentVariable("item_name", job1_name);
var job2_id = data[count].options[0].id;
postman.setEnvironmentVariable("item_id", job2_id);
var job3_id = data[count].options[0].options[1].id;
postman.setEnvironmentVariable("svc_optn_optn_id", job3_id);
var job4_name = data[count].options[0].options[1].name;
postman.setEnvironmentVariable("svc_optn_optn_name", job4_name);
}
const data = JSON.parse(responseBody);
data.forEach(item => {
console.log(item.id); // deliver object id.
item.options.forEach(option => {
console.log(`Option Id ${option.id}`); // option id
postman.setEnvironmentVariable("service_id", option.id);
option.options(optionItem => {
if(optionItem.name == 'Toothbrush'){
postman.setEnvironmentVariable("svc_optn_optn_name", optionItem.name);
postman.setEnvironmentVariable("svc_optn_optn_id", optionItem.id);
}
});
});
});

How do I use a function inside another function's function

I am trying to capitalize the first letter of each word in the other function.
This is the function to turn each words first letter to capital that I am using.
function capital_letter(str)
{
str = str.split(" ");
for (var i = 0, x = str.length; i < x; i++) {
str[i] = str[i][0].toUpperCase() + str[i].substr(1);
}
return str.join(" ");
}
Here’s the second function that I’m trying to use the first one in, but it is not working.
$(document).ready(function() {
$('#list').dataTable({
"ajax":{
url :"list.php",
type: "GET",
error: function(){
$("#post_list_processing").css("display","none");
}
},
"columns": [
{ "data": function capital_letter(item) {
return item.title;
}
},
{ "data": "description" },
{ "data": "time" }
]
});
});
You should only call the function like the following:
$(document).ready(function() {
$('#list').dataTable({
ajax: {
url: 'list.php',
type: 'GET',
error: function() {
$('#post_list_processing').css('display', 'none');
},
},
columns: [{
data: capital_letter(item.title);
},
{ data: 'description' },
{ data: 'time' },
],
});
});
You're redefining the function instead of actually using it... Call it like this;
...
"columns": [
{ "data": capital_letter(item.title) }
...
You are not calling the function correctly. Change the following in your code.
"columns": [
{ "data": capital_letter(item.title) }
Created a working snippet.
function capital_letter(str) {
str = str.split(" ");
for (var i = 0, x = str.length; i < x; i++) {
str[i] = str[i][0].toUpperCase() + str[i].substr(1);
}
return str.join(" ");
}
const columns = [{
"data": capital_letter("abc")
},
{
"data": "description"
},
{
"data": "time"
}
]
console.log(columns)

I need to loop this array

I use ajax to get a array from Economic and i would like to loop though it. The array (sortned):
{
"collection": [
{ "customerNumber": 1, "email": "jo+billing#test.com", "name": "Tester Test" }
, { "customerNumber": 2, "name": "Demo Name" }
]
, "metaData": { "more array" }
, "pagination": { "more array"}
, "self": "some url"
}
The jquery I think I need to use but give me a error: (TypeError: cannot use 'in' operator to search for 'length' in '{
"collectio...')
$.ajax({}).always(function (data) {
var options = $('#example').attr('options');
var substr = JSON.stringify(data, null, 4);
//-----------loop part------------
$.each((substr), function(i, val1) {
$.each(val1.customerNumber, function(a, val3) {
var CustInfo = val1[a]["name"] + " " + val1[a]["email"];
options[options.length] = new Option(CustInfo, val1[a]["customerNumber"]);
});
});
});
I am only interested in the values in "collection" and I want a select box with the customers info in it. like this:
<select>
<option value="1">Tester Test jo+billing#test.com</option>
<option value="2">Demo Name</option>
</select>
First, you don't have to use JSON.stringify() that will convert your response object data to a string that you can't loop through the attributes.
I am only interested in the values in "collection".
Then no need for two loops just use the data.collection :
$.ajax({}).always(function (data) {
var options = $('#example').attr('options');
$.each((data.collection), function(i, obj) {
var CustInfo = obj["name"] + " " + obj["email"];
options[options.length] = new Option(CustInfo, obj["customerNumber"]);
});
});
data = {
"collection": [{
"customerNumber": 1,
"email": "jo+billing#test.com",
"name": "Tester Test"
}, {
"customerNumber": 2,
"name": "Demo Name"
}],
"metaData": [],
"pagination": [],
"self": "some url"
};
$.each((data.collection), function(i, val1) {
var CustInfo = val1["name"] + " " + val1["email"];
console.log(CustInfo, val1["customerNumber"]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

loop through json javascript

I got a json which looks like something like this :
var json = {
"stock1" : {
"positions" : [{
"date": "29/02/2016",
"price": 15,
"type": "short"
}]
},
"stock2" : {
"positions" : [{
"date": "29/02/2016",
"price": 20,
"type": "long"
}]
}
};
For the moment I have something like that :
<script>
function myFunction() {
;
}
</script>
<div id = "short">
<button onclick="myFunction()">
short
</button>
</div>
My json is actually bigger than this example. I'd like to loop through it to get only the positions who are "short" and print them.
What is the best way to do that using only javascript ?
EDIT :
This is my new code but I still can't access to short or long position :
var stocks = [];
var longOnMarket = [];
var shortOnMarket = [];
var typeOfPosition = [];
var lolz = [];
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
lolz.push(JSON.stringify(item));
stocks.push(key);
var json2 = json[item];
for (var key2 in json2) {
if (json2.hasOwnProperty(key2)) {
var longOrShort = json2[key2].positions;
typeOfPosition.push(JSON.stringify(longOrShort));
}
}
}
}
alert(stocks);
alert(lolz);
alert(typeOfPosition);
What you can do is
var json = {
"stock1" : {
"positions" : [{
"date": "29/02/2016",
"price": 15,
"type": "short"
}]
},
"stock2" : {
"positions" : [{
"date": "29/02/2016",
"price": 20,
"type": "long"
}]
}
};
var object = JSON.parse(json);
for (var key in object) {
//Do your stuff
}
This solution looks for the array of positions and returns the object if some short is found.
var object = { "stock1": { "positions": [{ "date": "29/02/2016", "price": 15, "type": "short" }] }, "stock2": { "positions": [{ "date": "29/02/2016", "price": 20, "type": "long" }] } },
short = {};
Object.keys(object).forEach(function (k) {
if (object[k].positions.some(function (a) { return a.type === 'short' })) {
short[k] = object[k];
}
});
document.write('<pre>' + JSON.stringify(short, 0, 4) + '</pre>');
You should simple iterate through your object keys
var result = [];
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
item.positions = item.positions.filter(function(el) { return el.type == 'short' });
result.push(item);
}
}
here is my try please check it out
var i,
shortTypePositionsArray = [],
shortTypeWholeObject = {};
$.each(json,function(key,value){
if(Object.keys(value) == "positions"){
for(i = 0;i<value.positions.length;i++){
if(value.positions[i].type == 'short')
{
shortTypePositionsArray.push(value.positions[i]);
shortTypeWholeObject[key] = value;
}
}
}
});
console.log(shortTypePositionsArray);
console.log(shortTypeWholeObject);

Categories