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

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>

Related

What is the correct way to handle this data using jQuery?

I have a list of html elements with data attributes, which I would like to assemble into a jQuery object and manipulate the values.
What is the best way to dynamically add these in an each loop so that I can easily access the data as so: data.name and data.name.prop?
I want all the naming conventions to be dynamic and based on the data.
I based my code on the top answer from here: How to create dynamically named JavaScript object properties?
So far I have:
$('.licences-list .data div').each(function(index) {
var data = {}
cats[$(this).find('p').data('cat')] = $(this).find('p').data('catname')
cats.push(data)
})
But when I try to iterate over the data array, like so:
$.each(cats, function(key, value){
$('<div class="card"><p>'+value+'</p></div>').appendTo('#commercial-licenses');
});
I just get [object Object] output... and I'm not sure why!
var data = {}
cats[$(this).find('p').data('cat')] = $(this).find('p').data('catname')
Each time you loop through, you're actually just adding an empty object (data) to your array (cats). You're then assigning a named property to that array (cats) which $.each has no idea about (it ignores them because it's iterating over an actual array).
My guess is you want an object map which is something like: var cats = { "f1": "feline 1", "f2": "feline " };
In that case what you want is:
var cats = {};
$('.licences-list .data div').each(function(index) {
cats[$(this).find('p').data('cat')] = $(this).find('p').data('catname')
})
If you want an array that contain more values than just strings (or whatever data you have added to the element), you create new objects each time and append them to the cats array:
var cats = [];
$('.licences-list .data div').each(function(index) {
cats.push({
'id': $(this).find('p').data('cat'),
'name': $(this).find('p').data('catname')
});
})
This will then give you an array that you can use $.each over, and access the values using: value.id, value.name
Don't over complicate it.
$('.div').attr('data-attribute', 'data-value');
using your example:
$('.licences-list .data div').attr('attribute-name', 'attribute-value');

How to get D3 csv data into a different variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I am trying to extract imdb data from a csv and put two elements of it into an array of objects. There are 10 fields. I only want to use 2 in my chart. I am trying this:
var mydata;
// Grab the data
d3.csv('./movies.csv', function(csv){
csv.forEach(function(d){
mydata += {rating: d.imdbRating,
winsNoms: d.WinsNoms };
});
});
console.log(mydata);
Can somebody explain exactly what is going on here and why I get undefined when I try to output mydata in the final line? Finally, how do I change it around so it works?
You should push objects into an array. See adjustments below:
var mydata = [];
// Grab the data
d3.csv('./movies.csv', function(csv){
csv.forEach(function(d){
mydata.push({
rating: d.imdbRating,
winsNoms: d.WinsNoms
});
});
});
console.log(mydata);
You’ll need to first declare an empty array. Then you can push items into it.
To only use part of the set, you can use “slice” to truncate the array.
var mydata = [];
// Grab the data
d3.csv('./movies.csv', function(csv){
csv.forEach(function(d){
mydata.push({rating: d.imdbRating,
winsNoms: d.WinsNoms });
});
});
console.log(mydata);

Handle multiple string in Array of String javascript [closed]

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);

Read a JSON list in list [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I have a json like this :
{
"Project
[id=1, dateDebut=2017-01-13, dateFin=2017-01-18, description=qsd, sponsor=qsd ]"
:
[
{"id":1,"title":"qsd ","description":"qsdqsd","dateFin":"2017-01-26"},
{"id":2,"title":"sss ","description":"sss","dateFin":"2017-01-26"}
]
}
originated from : return new ObjectMapper.write(Map<Project,List<Task>> projectTasks = new LinkedMultiValueMap<>()) ;
EDIT : this is the real response :
{"Project [id=1, name=qsdsqd, type=null, done=false, dateDebut=2017-01-13, dateFin=2017-01-18, description=qsd, sponsor=qsd, client=qsd, showable=true]":
[{"id":1,"title":"qsd ","description":"qsdqsd","dateFin":"2017-01-26","dateDebut":"2017-01-14","period":null,"done":false,"status":"Actif","priority":"Normal"},
{"id":2,"title":"task 2 ","description":"qsdqsd","dateFin":"2017-01-26","dateDebut":"2017-01-14","period":null,"done":false,"status":"Actif","priority":"Normal"}]}
How can I read the list of tasks in the client side ?
First of all, your JSON is not valid. Are you sure that is a line break between the word Project and [id...]. A valid JSON would be:
{
"Project [id=1, dateDebut=2017-01-13, dateFin=2017-01-18, description=qsd, sponsor=qsd, ]":
[
{"id":1,"title":"qsd ","description":"qsdqsd","dateFin":"2017-01-26"},
{"id":2,"title":"sss ","description":"sss","dateFin":"2017-01-26"}
]
}
You can have object key names like that. But i'ts not very friendly to retrieve data.
If you cannot change your data schema (or just don't want), you can iterate over the Object with the
Object.keys(obj).forEach ( (key) => {
console.log('key: ' + key);
console.log('value: ' + obj[key]);
/* you can iterate over your value (tasks) here */
obj[key].forEach( (task) => {
console.log('task1: ', task);
});
}); //where obj is your json
Or you can access the first object property with:
obj[Object.keys(obj)[0]]; //where obj is your json
EDIT As pointed by #André Dion, forEachis best suited to iteration, not map. And we're assuming your response is already parsed from the server (by yourself or by a lib like jquery). If not, you should do a JSON.parse(response); to retrieve the object.
You may try this:
Assume above response in stored in var response.
for(var project in response) { // this will get every project
for(var i=0; i<project.length; i++) { // this will iterate over the array for each project which are your tasks.
console.log("task" + project[i]);
console.log(project[i]["id"]); // access each tasks id, similar for other attributes
}
}

How to open json file with objects in d3? [duplicate]

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 6 years ago.
I want to load one json file for a d3 world map (based on: http://datamaps.github.io/) and a d3 bar chart (based on: https://bl.ocks.org/mbostock/3885304).
My JSON looks like this:
{
"CHE": {"costOfLivingIndex": "123.10", "propertyPriceToIncomeRatio": "123.10", "qualityOfLifeIndex": "208.54", "name": "Switzerland", "purchasingPower": "178.74", "pollutionIndex": "28.73", "trafficCommuteTimeIndex": "8.57", "health Care Index": "68.88", "climateIndex": "23.02", "safetyIndex": "74.27"},
"DNK": {"costOfLivingIndex": "84.88", "propertyPriceToIncomeRatio": "84.88", "qualityOfLifeIndex": "206.49", "name": "Denmark", "purchasingPower": "142.14", "pollutionIndex": "25.64", "trafficCommuteTimeIndex": "5.85", "health Care Index": "81.89", "climateIndex": "29.93", "safetyIndex": "74.33"}
etc...
}
I choose this lay for the d3 world map. However, how I am wondering how I can iterate through properties of the objects. If I do for instance:
console.log(data.DNK.name);
I get the name, but how can get a list with all the names (or other values)?
we you could do something like:
for (var key in data) {
alert(key + " -> " + data[key]);
}
you should be able to get the other parameters via data[key]
As it is already JSON object you can loop through it without using JSON.parse which you would use if it were string or sth.
for(var key in data){
console.log(key);
for(var k in data[key]){
console.log(k,data[key][k]);
}
}

Categories

Resources