This question already has answers here:
Why does a string index in an array not increase the 'length'?
(7 answers)
Closed 7 years ago.
Demo
Why does associative array qaObj return 0 length?
$(function(){
var data = "Q$:I am in.A$: out Q$:whats this A$:Answer";
alert("in");
var str = $.trim(data).replace(/(\r\n|\n|\r)/gm,"");
var qaObj = new Array();
if(str != null && str.indexOf("A$:") != -1 && str.indexOf("Q$:") != -1){
var qaPairs = str.split("Q$:"); /**Eliminate first header part**/
qaPairs.shift();
alert(qaPairs);
for(var counter = 0; counter < qaPairs.length; counter++){
var qaSplittedArr = qaPairs[counter].split("A$:");
qaObj[qaSplittedArr[0]] = qaSplittedArr[1];
}
}
alert(qaObj);
alert(qaObj["I am in."]);
});
I am not able to send qaObj to php. It shows empty array. So I am not able to loop through.
Why is it happening?
I am sending through ajax.
qaObj needs to be an object ({}) here, not an array (new Array()). JavaScript objects are the equivalents of PHP's associative arrays. Updated fiddle: http://jsfiddle.net/p6p8jezu/4/
$(function(){
var data = "Q$:I am in.A$: out Q$:whats this A$:Answer";
var str = $.trim(data).replace(/(\r\n|\n|\r)/gm,"");
var qaObj = {};
if(str != null && str.indexOf("A$:") != -1 && str.indexOf("Q$:") != -1){
var qaPairs = str.split("Q$:"); /**Eliminate first header part**/
qaPairs.shift();
alert(qaPairs);
for(var counter = 0; counter < qaPairs.length; counter++){
var qaSplittedArr = qaPairs[counter].split("A$:");
qaObj[qaSplittedArr[0]] = qaSplittedArr[1];
}
}
alert(JSON.stringify(qaObj));
alert(qaObj["I am in."]);
});
Try making use of pure Javascript objects instead of arrays.
Change the new Array() to {} in order to make an object.
var qaObj = {};
Now you can do your favorite PHP-like associative array assignment on this object as such and achieve the desired result:
qaObj[qaSplittedArr[0]] = qaSplittedArr[1];
Check your console in this DEMO.
Note that the recommended approach to insert elements to an array is to use .push() method, and not as PHP-like syntax that you've used.
Related
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 3 years ago.
I'm trying to display a specific property of multiple objects from the response of an axios call (using .innerHTML) but I can only get it to display one result of the array.
function getMusic(searchText){
if (artistButton.checked) {
axios.get('https://cors-anywhere.herokuapp.com/https://api.deezer.com/search/?q=artist:"'+searchText+'"')
.then(function(response){
console.log(response);
var artist = response.data.data;
for (var i = 0; i < artist.length; i++){
var artistResult = artist[i].artist.name;
console.log(artistResult);
}
document.getElementById("music").innerHTML = artistResult;
});
//tried using document.getElementById("music").innerHTML = artistResult.join(" "); but it gives me a TypeError
Since you declare artistResult inside the loop, you are clearing its value and storing only one name every time. Also, it's giving you a TypeError because artistResult is a String and join() is a method of Array.
To solve the problem you can use an array to push the values and then join it:
var artistResult = [];
for (var i = 0; i < artist.length; i++){
artistResult.push(artist[i].artist.name)
console.log(artistResult);
}
document.getElementById("music").innerHTML = artistResult.join(" ");
Or concatenate the names in a string:
var artistResult = "";
for (var i = 0; i < artist.length; i++){
artistResult += " " + artist[i].artist.name
console.log(artistResult);
}
document.getElementById("music").innerHTML = artistResult;
Youre artistResult variable is being overridden for each iteration of the loop. Only the last artist name is referenced by the variable when the loop ends. You can store the artist names in an array if you want to display it later.
var artistResult = [];
for (var i = 0; i < artist.length; i++){
artistResult.push(artist[i].artist.name);
}
You can try this
var searchText='A'
axios.get(`https://cors-anywhere.herokuapp.com/https://api.deezer.com/search/?q=artist:${searchText}`)
.then(function(response){
let artists_list=response.data.data.map(x=>`<li>${x.artist.name}</li>`).join("");
document.getElementById("music").innerHTML = artists_list;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.js"></script>
<ul id="music"></ul>
This question already has answers here:
How to find an appropriate object in array by one of its properties
(3 answers)
Closed 6 years ago.
Hi I have a json string
"{"data":[{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":15,"ConfigName":"Offline Days","ConfigValue":"Sunday"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}]}"
I want to check ConfigValue of ConfigName "CurrentTime".
Currently I am accessing it by below code
var d = JSON.parse(data).data;
d[2].ConfigValue
but sometimes the json string will be
"{"data":[{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}]}"
according to above string now if i want to access "CurrentTime"
I will have to write below code
var d = JSON.parse(data).data;
d[1].ConfigValue
So can anyone tell how to access it? Because the array may change anytime so I cannot hardcode the array index like that.
You can run a loop and check the value of ConfigName. Below is the code
var data = '{"data":[{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":15,"ConfigName":"Offline Days","ConfigValue":"Sunday"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}]}';
var d = JSON.parse(data).data;
for(var i=0; i<d.length; i++)
{
if(d[i].ConfigName === 'CurrentTime')
{
alert(d[i].ConfigValue); //Do stuff with the value.
}
}
You have same quotes inside and outside string without escaping. But maybe it takes place only in question texts.
In this case You need to check every item like this:
for (var i in d) {
if (d[i].Id == 0) {
alert(d[i].ConfigName);
}
}
You can try this:
var k = {"data":[{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":15,"ConfigName":"Offline Days","ConfigValue":"Sunday"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}]}
var result = $(jQuery.parseJSON(JSON.stringify(k))).each(function() {
var configName = this.ConfigName;
var configValue = this.ConfigValue;
});
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You first need to find the object in the array with "ConfigValue" equal to "CurrentTime". Once you have this object, you can simply access its "CongigValue" property.
var json1 = {"data":
[
{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":15,"ConfigName":"Offline Days","ConfigValue":"Sunday"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}
]
};
var json2 = {"data":
[
{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}
]
};
var currentTime = findCurrentTime( json1 );
console.log( "currentTime: " + currentTime );
var currentTime = findCurrentTime( json2 );
console.log( "currentTime: " + currentTime );
function findCurrentTime( jsonObj )
{
var filteredArray = jsonObj.data.filter(function(element){
return element.ConfigName === "CurrentTime";
});//filter()
if( filteredArray.length > 0 )
return filteredArray[0].ConfigValue;
return false;
}//findCurrentTime()
I have the following array and a loop fetching the keys (https://jsfiddle.net/ytm04L53/)
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
alert(feed.match(/\d+$/));
}
The array will always contain different number of keys, What I would like to do is either use these keys as variables and assign the value after the : semicolon as its value or just create a new set of variables and assign the values found on these keys to them.
How can I achieve this? so that I can then perform some sort of comparison
if (test_user > 5000) {dosomething}
update
Thanks for the answers, how can I also create a set of variables and assign the array values to them? For instance something like the following.
valCount(feeds.split(","));
function valCount(t) {
if(t[0].match(/test_user_.*/))
var testUser = t[0].match(/\d+$/);
}
Obviously there is the possibility that sometimes there will only be 1 key in the array and some times 2 or 3, so t[0] won't always be test_user_
I need to somehow pass the array to a function and perform some sort of matching, if array key starts with test_user_ then grab the value and assign it to a define variable.
Thanks guys for all your help!
You can't (reasonably) create variables with dynamic names at runtime. (It is technically possible.)
Instead, you can create object properties:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":"); // Splits the string on the :
obj[parts[0]] = parts[1]; // Creates the property
});
Now, obj["test_user_201508_20150826080829.txt"] has the value "12345".
Live Example:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":");
obj[parts[0]] = parts[1];
});
snippet.log(obj["test_user_201508_20150826080829.txt"]);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
You can do it like this, using the split function:
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
console.log(feed.split(/[:]/));
}
This outputs:
["test_user_201508_20150826080829.txt", "12345"]
["test_user_list20150826", "666"]
["test_list_Summary20150826.txt", "321"]
Use the split method
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
feedMap = {}
for (i = 0; i < feeds.length; i++) {
var temp = feeds[i].split(':');
feedMap[temp[0]] = temp[1];
}
Yields:
{
"test_user_201508_20150826080829.txt":"12345",
"test_user_list20150826":"666",
"test_list_Summary20150826.txt":"321"
}
And can be accessed like:
feedMap["test_user_201508_20150826080829.txt"]
Here is a codepen
it is not very good idea but if you really need to create variables on-the-run here's the code:
for (i = 0; i < feeds.length; i++)
{
var feed = feeds[i];
window[feed.substring(0, feed.indexOf(":"))] = feed.match(/\d+$/);
}
alert(test_user_201508_20150826080829)
Of course you cannot have any variable-name-string containing banned signs (like '.')
Regards,
Michał
This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Check url parameter using javascript
(3 answers)
Closed 9 years ago.
I'm aware of window.location.host and window.location.pathname, but is there anyway to pull the extra parameters of a link like this?
http://www.example.com/test?u=123
I would like to end up with a dynamic variable that is equal to "u123" but without the double quotes.
Thanks!
var oGetVars = {};
if (window.location.search.length > 1) {
for (var aItKey, nKeyId = 0, aCouples = window.location.search.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) {
aItKey = aCouples[nKeyId].split("=");
oGetVars[unescape(aItKey[0])] = aItKey.length > 1 ? unescape(aItKey[1]) : "";
}
}
// alert(oGetVars.yourVar);
window.location! MDN window.location
For a basic example of getting all the page parameters into a usable variable try this:
var pageParams = {};
if(location.search != ''){
var searchStr = location.search;
searchStr = searchStr.substr(1);
var searchStrArr = searchStr.split('&');
var pageParamPair, pageParamKey, pageParamValue;
for(var i=0;i<searchStrArr.length;i++){
pageParamPair = searchStrArr[i].split('=');
pageParamKey = pageParamPair[0];
pageParamValue = pageParamPair[1];
pageParams[pageParamKey] = pageParamValue;
}
}
thus in your case pageParams['u'] = "123"
This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 8 years ago.
I am creating my own object:
gridObject = new Object();
I am then using jquery to pull the contents of list item tags, which themselves are filled with tags that have specific class names:
<li row="1"><p class="department" rowitem="department">Photography</p>...</li>
I am pulling them using this code:
//make object from results
gridObject = new Object();
//get all the rows
var rowlist = $('li[row]');
for(var r=0; r<rowlist.length; r++) {
//make gridObject row element here
//get the row content
var thisrow = $(rowlist[r]).html();
//get all the p tags
var rowitems = $(thisrow + 'p.[rowitem]');
//get field name
for(var ri=0; ri<rowitems.length; ri++) {
if (r < 2) { //this is temporary just for testing
var fieldname = $(rowitems[ri]).attr('rowitem');
var fieldvalue = $(rowitems[ri]).html();
}
}
Ia m getting hung up passing this into my object. Two questions. Can an object property be made with a variable name, like so
griObject.fieldname = fieldvalue;
and can the objects have parent/child relationships such as:
gridObject.r.fieldname = fieldvalue;
in this case both r and fieldname would be variables. Or should I just be working associative arrays to achieve something similar?
This is in answer to a follow up question I posted below: "Is there a print_r equivalent in javascript" - you can use iterator, a bit more typing but does the trick:
//loop through search data
var it = Iterator(filteritems);
for(var pair in it) {
console.log("key:" + pair[0] + ", value:" + pair[1] + "\n");
}
If you want to use a variable property name, use subscript syntax:
var fieldname = 'test';
//These two lines are equivalent as long as fieldname is 'test':
gridObject[fieldname] = fieldvalue;
gridObject.test = fieldvalue