How to convert select2 array output to single string? - javascript

How to convert select2 array output to single string (separated by comma)? Just like this "task_owner":"Administrator,abc2". Current output is separated by comma but in single array "task_owner":["Administrator","abc2"]. This is because the DB is received by string, not array.
Another question, how to re-convert back to array since during editing, Ajax will send that String from DB and I maybe need to convert back to Array for display purpose.
I was referred to this Link but not working.
<form id="myForm">
<select type="text" class="form-control myClass" id="myID" multiple="multiple"></select>
</form>
$('.myClass').select2({
tags: true
});
$('#btnSubmit').on('click',function(){
var testOutput = ""; // I put this because an error appear so I create a new var but the output is = "null", why?
var owner = $('#myID').val();
if (owner.val() !== null && owner.val().length > 0){
var testOutput = $('#myID') = owner.val().join(',');
testOutput = Object.assign({}, {task_owner: testOutput.task_owner.join(",")})
}
// parameter that need to send to API
var obj = {
task_owner : testOutput,
// Another parameter...
};
var params = JSON.stringify(obj);
$.ajax({
// My Ajax Condition...
});
});

As dicussed:
$(".myClass").select2({
tags: true
});
$("#btnSubmit").on("click", function() {
var testOutput = ""; // I put this because an error appear so I create a new var but the output is = "null", why?
var owner = $("#myID").val(); //
if (Array.isArray(owner) && owner.length) {
testOutput = owner.join(",");
}
var obj = {
task_owner: testOutput
};
var params = JSON.stringify(obj);
$.ajax({
// My Ajax Condition...
});
});

Related

What's wrong in this script?

When I submit the form and I try to get the Roomsno input value its showing like
this-
Array ( [0] => 1,2 ); why???
How can I send it so that it will come as a real array means like this-
Array([0]=>1 [1]=>2)
<input type="hidden" class="form-control" name="Roomsno" id="Roomsno" required>
<script>
var rmidarray = []; // new Array()
var rmnoarray = [];
$('.roomtype').change(function() {
roomss_id = $(this).attr('data-id');
no_room = $(this).val();
var check = rmidarray.includes(roomss_id);
if (check == true) {
// alert('hi')
index = rmidarray.indexOf(roomss_id);
// alert(index);
rmnoarray.splice(index, 1, no_room);
// rmnoarray[index].push(no_room);
} else if (check == false) {
// alert('by');
rmidarray.push(roomss_id);
rmnoarray.push(no_room);
} else {
alert('No rooms Selected!!!')
}
$("#Roomsno").val(rmnoarray);
});
</script>
As the value is in array format so Rather than setting the value directly use jason.stringfy-
Ex.
$("#Roomsno").val(rmnoarray); //Instead of this one
$('#Roomsno').val(JSON.stringify(rmnoarray)); //This one worked for me
And when i try to get the value i use json.decode and the value will come as array and we can use it normally as we use array. The array will come like- Array([0]=>1[1]=>2)

Create JavaScript array from excel data using JavaScript and JSON

I'm trying to read and parse an excel file and create a JavaScript array object with the data.
The excel file will look like:
AA11 AA22 AN65
AB11 AB22 AN64
...
And I want the JavaScript array to look like:
[[AA11, AA22, AN65], [AB11, AB22, AN64],...]
So far I have the following code:
<input type="file" id="input" accept=".xls,.xlsx,.ods" />
<a id="result"></a>
<script type="text/javascript">
$("#input").on("change", function(e) {
var file = e.target.files[0];
if (!file) return;
var FR = new FileReader();
function byDocument(e) {
var data = new Uint8Array(e.target.result);
var workbook = XLSX.read(data, { type: "array" });
var firstSheet = workbook.Sheets[workbook.SheetNames[0]];
var result = XLSX.utils.sheet_to_json(firstSheet, { header: 1 });
var output = document.getElementById("result");
output.innerHTML = JSON.stringify(result, null, 2);
window.alert(result);
window.alert(result.type);
var array;
array = output.innerHTML;
output.parentNode.removeChild(output);
return array;
}
FR.onload = function(e) {
array = byDocument(e);
window.alert(array);
array.type = Array;
window.alert(array.type);
window.alert(array.length);
};
FR.readAsArrayBuffer(file);
});
</script>
This outputs text on the document that looks like an array, but when I try to store the data in a variable and index the array, it views the element array as some sort of string, or undefined. I'm wondering how to parse the excel file, or convert the JSON string, so that it behaves like a JavaScript array, which I could then index.
I believe it should be array = result instead of array = output.innerHTML. Or, at least, array = JSON.parse(ourput.innerHTML), because innerHTML is not an array, it's a string (you got it by JSON.strigify before).
It seems like you are already turning your result into JSON here:
var result = XLSX.utils.sheet_to_json(firstSheet, { header: 1 });
According to the documents of xlsx this will convert your excel file into workable JSON. So result might be the value you need to return instead of array in your byDocument function.
The line output.innerHTML = JSON.stringify(result, null, 2); will turn the object into JSON and put it in the DOM.
const myJSObject = JSON.parse(myJSON) will return a JavaScript object and assign it to a variable.
I took a few of the DOM lines out of your function to make it less confusing, so you could try replacing your function with:
function byDocument(e) {
var data = new Uint8Array(e.target.result);
var workbook = XLSX.read(data, { type: "array" });
var firstSheet = workbook.Sheets[workbook.SheetNames[0]];
var result = XLSX.utils.sheet_to_json(firstSheet, { header: 1 });
var array;
array = result
return array;
}

How to get value stored in array object in javascript

I m storing values as object which i get dynamically, now i need to retrieve those values, its simple question but i didnt get the answer so i asked here.
for example:
/* Adding values dynamically into array of saveData. */
at first :
id = 1
gettext = 'Y'
text = 'Hello world'
at second :
id = 2
gettext = 'N'
text = 'JavaScript'
etc....
My code:
var saveData = {};
var objterm = {};
objterm["valueID"] = id;
objterm["valueGot"] = gettext;
objterm["text"] = text;
saveData[id] = objterm; // Saving values in array...
How can i retrive a value eg: say, saveData[1] -> gettext, text
// I tried the below to get value as
var obj = _.find(saveData, function(obj) { return obj.id == id }); // did nt get values
From the code you provided both saveData and objterm are simple objects, so if you wanted to retrieve specific data from some specific entry to saveData all you need to do is this:
saveData[id].valueGot
based on
objterm["valueID"] = id;
objterm["valueGot"] = gettext;
objterm["text"] = text;
It is working after adding http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js
For _.find & _.findWhere method.
var saveData = {};
var objterm = {};
objterm["valueID"] = 1;
objterm["valueGot"] = 'Y';
objterm["text"] = 'javascript';
saveData[1] = objterm;
var obj = _.find(saveData, function(obj) { return obj.valueID == 1 });
var obj2 = _.findWhere(saveData, {valueGot: 'Y' });
console.log(obj)
console.log(obj2)
https://jsfiddle.net/anil826/7ay25qwu/

Creating a JSON dynamically with each input value using jquery

I got a situation where I would like to read some data off a JSON format through PHP, however I am having some issues understanding how I should construct the Javascript object to create the JSON format dynamically.
My scenario is as follows:
<input title="QA" type="text" class="email">
<input title="PROD" type="text" class="email">
<input title="DEV" type="text" class="email">
The Javascript code I have so far goes through each input grabs the data, I am however unable to understand how to process from here on.
var taskArray = {};
$("input[class=email]").each(function() {
var id = $(this).attr("title");
var email = $(this).val();
//how to create JSON?
});
I would like to get the following output if possible.
[{title: QA, email: 'a#a.com'}, {title: PROD, email: 'b#b.com'},{title: DEV, email: 'c#c.com'}]
Where the email is acquired by the input field value.
Like this:
function createJSON() {
jsonObj = [];
$("input[class=email]").each(function() {
var id = $(this).attr("title");
var email = $(this).val();
item = {}
item ["title"] = id;
item ["email"] = email;
jsonObj.push(item);
});
console.log(jsonObj);
}
Explanation
You are looking for an array of objects. So, you create a blank array. Create an object for each input by using 'title' and 'email' as keys. Then you add each of the objects to the array.
If you need a string, then do
jsonString = JSON.stringify(jsonObj);
Sample Output
[{"title":"QA","email":"a#b"},{"title":"PROD","email":"b#c"},{"title":"DEV","email":"c#d"}]
I don't think you can turn JavaScript objects into JSON strings using only jQuery, assuming you need the JSON string as output.
Depending on the browsers you are targeting, you can use the JSON.stringify function to produce JSON strings.
See http://www.json.org/js.html for more information, there you can also find a JSON parser for older browsers that don't support the JSON object natively.
In your case:
var array = [];
$("input[class=email]").each(function() {
array.push({
title: $(this).attr("title"),
email: $(this).val()
});
});
// then to get the JSON string
var jsonString = JSON.stringify(array);
May be this will help, I'd prefer pure JS wherever possible, it improves the performance drastically as you won't have lots of JQuery function calls.
var obj = [];
var elems = $("input[class=email]");
for (i = 0; i < elems.length; i += 1) {
var id = this.getAttribute('title');
var email = this.value;
tmp = {
'title': id,
'email': email
};
obj.push(tmp);
}
same from above example - if you are just looking for json (not an array of object) just use
function getJsonDetails() {
item = {}
item ["token1"] = token1val;
item ["token2"] = token1val;
return item;
}
console.log(JSON.stringify(getJsonDetails()))
this output ll print as (a valid json)
{
"token1":"samplevalue1",
"token2":"samplevalue2"
}
I tried this:
// Sample JS object
var varobject = {
name: "Name",
Intern: "Test",
};
// Converting JS object to JSON string
JSON.stringify(varobject);

Push to array a key name taken from variable

I have an array:
var pages = new Array();
I want to push my pages data to this array like this:
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
pages_order.push({datatype:info});
});
but this code doesn't replace datatype as variable, just puts datatype string as a key.
How do I make it place there actual string value as a key name?
I finally saw what you were trying to do:
var pages = new Array();
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
var temp = {};
temp[datatype] = info;
pages_order.push(temp);
});
$('li.page').each(function () {
//get type and info, then setup an object to push onto the array
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
obj = {};
//now set the index and the value for the object
obj[datatype] = info;
pages_order.push(obj);
});
Notice that you can put a comma between variable declarations rather than reusing the var keyword.
It looks like you just want to store two pieces of information for each page. You can do that by pushing an array instead of an object:
pages_order.push([datatype, info]);
You have to use datatype in a context where it will be evaluated.
Like so.
var pages = [];
$('li.page').each(function () {
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
record = {};
record[datatype] = info;
pages_order.push(record);
});
You only need one var it can be followed by multiple assignments that are separated by ,.
No need to use new Array just use the array literal []
You may add below single line to push value with key:
pages_order.yourkey = value;

Categories

Resources