Handle multiple string in Array of String javascript [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am getting data in array like this, left side are account name and right one are subscriptions.
7ef:" 3sdc 12exf"
12ef:" 8ecg"
10ef:" 3ecf 3egf 3elm 3ecf 3egf 3elm "
mean 7ef index have 2 strings of data and there is space between both. and 10ef have 6 strings of data.I need this data in form of like
7ef:" 3sdc"
7ef:" 12exf"
12ef:" 8ecg"
10ef:" 3ecf "
10ef:"3egf"
10ef:"3elm"
10ef:"3ecf"
10ef:"3egf"
10ef:"3elm "
As I have to sent it to make its csv file. How Can I do that in javascript ?
Code of creating this is like
foreach ($subscriptions as $subscription) {
$str=$str.' '.$subscription->uuid;
}$anew[account[$i]]=$str;
EDIT :
Now after reading comments can some one tell me how can I make it like
0:" 3sdc"
1:" 12exf"
2:" 8ecg"
like I will save account for later and now I want to arrange them all.

This won't be possible because Javascript Object at same level can have only have unique key, so it will just override the value
SUGGESTED:
use the structure like this
{
7ef:["3sdc", "12exf"],
12ef:["8ecg"],
10ef:["3ecf","3egf", "3elm", "3ecf", "3egf", "3elm"]
}
code :
for (var keys in a){
for (var data in a[keys]){
console.log(keys + " : "+ data)
}
}
a is the var holding the above js object

Change your PHP code to produce a better structure:
$lst = [];
foreach ($subscriptions as $subscription) {
$lst[] = $subscription->uuid;
}
$anew[account[$i]] = $lst;
I suppose you have somewhere:
echo json_encode($anew);
This will give you the following structure in JavaScript:
{
"7ef": ["3sdc", "12exf"],
"12ef": ["8ecg"],
"10ef": ["3ecf","3egf", "3elm", "3ecf", "3egf", "3elm"]
}
To output this as CSV, you could do this (assuming the data is in response):
const response = {
"7ef": ["3sdc", "12exf"],
"12ef": ["8ecg"],
"10ef": ["3ecf","3egf", "3elm", "3ecf", "3egf", "3elm"]
};
const csv = Object.keys(response).reduce( (acc, key) =>
acc.concat(response[key].map( uuid => [key, uuid].join(", ") ))
, []).join("\n");
console.log(csv);

Related

How to make the Select option appending with html? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed last year.
Am making an select option from ajax success. The problem is that, the results are array so i need to manipulate the array with some html.
My appending code:
data = [['2022-02-01', '2022-02-02'],['2022-03-01', '2022-03-02'],['2022-04-01', '2022-04-02']]
$("#id_course").change(function () {
$('select[id=id_intakes]').empty().prepend("<option></option>");
$.each(data, function(index, date){
$('select[id=id_intakes]').append(
$('<option></option>').attr("value",date).text(date)
)
});
})
Just creates the select correctly, but it displays the array as it is. The dropdown contains all the three values array
['2022-02-01', '2022-02-02']
['2022-03-01', '2022-03-02']
['2022-04-01', '2022-04-02']
I need to manipulate this like
From:2022-02-01 & To:2022-02-02
From:2022-03-01 & To:2022-03-02
From:2022-04-01 & To:2022-04-02
So how to do this ?
You can add this to your code:
name = `From:${name[0]} & To:${name[1]}`;
Demo
data = [
['2022-02-01', '2022-02-02'],
['2022-03-01', '2022-03-02'],
['2022-04-01', '2022-04-02']
]
$('select#id_intakes').empty().prepend("<option></option>");
$.each(data, function(index, name) {
name = `From:${name[0]} & To:${name[1]}`;
$('select[id=id_intakes]').append(
$('<option></option>').attr("value", name).text(name)
)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="id_intakes"></select>

Javascript:-Embedded "For Loop" is not working in HTML [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I was trying to implement a for loop embedded in HTML to print the values in an array. This is what I did:
var arr = [];
for (var id in order.cart.items) {
arr.push(order.cart.items[id]);
}
console.log()
let mailOptions = {
from: "John Doe"+"<johndoe#gmail.com>", // TODO: email sender
to:email , // TODO: email receiver
subject: 'Order Confirmation',
html: "<script>"+"<br>"+ "var i;"+ "<br>" +
"for("+"i="+0+";"+"i<"+arr.length+";"+"i++" +")"+"{"+arr[i].item.title+"}"+"<br>"+"</script>"}
The problem is with the html part in mailOptions. The for loop does not seem to be working. The array is getting values, but the error shown is: i is not defined. How can I do this? What is wrong in the above syntax? The array is working properly. If I put arr[0] or arr[1] in place of arr[i], everything works properly
The only instance of i I see in this code is +arr[i].item.title+.
But you don't have the variable i declared inside this script that's making this mailOptions, only inside the script tag you're trying to write inside the mailOptions html.
Maybe I'm missing something or we're missing part of the code ( is this code part of some other for-loop that's not shown? Otherwise it seems logical to me that the i is not defined error is about this script, not the embedded one.
EDIT:
Alot of things do not make sense here, since arr and i are not part of the same script, but i think you might be looking for this instead of embedding a script tag:
var order = {
cart: {
items: {
id_123: { item: { title: "val123" }},
id_456: { item: { title: "val456" }},
id_789: { item: { title: "val789" }}
}
}
};
var arr = [];
for (var id in order.cart.items) {
arr.push(order.cart.items[id]);
}
var email = 'a#a.vcom';
var html = '';
var i;
for ( i=0;i<arr.length;i++) {
html += arr[i].item.title + '<br>';
}
let mailOptions = {
from: "John Doe"+"<johndoe#gmail.com>", // TODO: email sender
to: email , // TODO: email receiver
subject: 'Order Confirmation',
html: html
};
console.log( mailOptions );
Is this what you're after? Including all the order items inside the email as HTML? instead of trying to embed a script tag?
I'm not sure, but i can imagine it has trouble parsing your embedded script. What is it you are trying to achieve? If you want to create a list of items, why don't you create a function instead, that returns a list of items in plain html?

Json parse by search id [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a json file like below:
{ "userdata": { "userid123": {"uname": " john", "uemail": "john#mail.com"}, "userid124": {"uname": "sam", "uemail": "sam#mail.com"} }
I want to parser user details if someone go to url http://example.com/?userid123
So only details of userid123 (which is in the url, get it from there) will be shown.
Json string you added to the question is wrong.
If you need to get the string after the question mark and test if the corresponding value exist or not, you can write:
var js = {
"userdata": {
"userid123": {"uname": " john", "uemail": "john#mail.com"},
"userid124": {"uname": "sam", "uemail": "sam#mail.com"}
}
};
var sp = window.location.search.substr(1);
//for testing purposes
sp='userid123';
if (js.userdata[sp] !== undefined) {
console.log('uname: ' + js.userdata[sp].uname + ' uemail: ' + js.userdata[sp].uemail)
}
First of all you have to save userId to variable like
var userId = location.search.substr(1);
.substr(1) <- this will remove ? from result of location.search();
Now since you are using jquery you can access your json (and user data) as below
$.getJSON( "users.json", function( data ) {
var userData = data[userId]; // your user data
}

Javascript SQLite: SELECT statement with WHERE IN clause [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
In Javascript SQLite, is there a better way we can execute a SELECT statement with WHERE IN clause? Let's take the following query as an example:
var ids = [1, 5, 10];
function getBranches (ids) {
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM Branch WHERE id in ?', [ids], function(tx,results){
// process results
});
});
}
I know we can always format the WHERE IN clause for the ids in a way SQL recognizes it as shown below. But I was wondering if there's a nice way to achieve that requirement.
function getBranches (ids) {
db.transaction(function(tx) {
var idClause = ' id in (\"' + ids.join("\",\"") + '\");';
tx.executeSql('SELECT * FROM Branch WHERE ' + idClause, [], function(tx,results){
// process results
});
});
}
Solution 1:
One way is to do without the placeholder ?:
'SELECT * FROM test WHERE col1 in (' + ids.join(',') + ')', [],...
Solution 2:
Another way is to do the fancy prepared statement style as in your example, where you need to put exact number of ? that equals the number of arguments.
var ids = [1, 5, 10];
var placeHolders = new Array(ids.length).fill('?').join(',');
var query = 'SELECT * FROM Branch WHERE id in ('+ placeHolders + ')';
tx.executeSql(query, [ids], ...

Changing JSON Object Format [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i got a JSOn object with over 200 entrys. Actually it looks like
params = {
key_a_1 : "value_a_1"
key b_1 : "value_b_1"
key_c_1 : "value_c_1"
key d_1 : "value_d_1"
key_a_2 : "value_a_2"
key b_2 : "value_b_2"
key_c_2 : "value_c_2"
key d_2 : "value_d_2"
}
and I need to convert it to
params = {
1
{
key_a : "value_a_1"
key b : "value_b_1"
key_c : "value_c_1"
key d : "value_d_1"
}
2
{
"key_a : value_a_2"
"key b : value_b_2"
"key_c : value_c_2"
"key d : value_d_2"
}
}
key can be named anything else but the number is always the id.
any idea whats the best way? thanks!
Basically the problem is, that I need the ID which is at the end of the key as an own array inside the JSON Object and my Javascript skills aren't great enough.
Just iterate over the properties and fill them into another object:
var newObject = {};
Object.keys(oldObject).forEach(function (key) {
var name = /(key_\w+)_\d+/.exec(key)[1],
index = /key_\w+_(\d+)/.exec(key)[1];
if (!newObject[index]) {
newObject[index] = {};
}
newObject[index][name] = oldObject[key];
});
console.log(newObject);

Categories

Resources