I'm working with adobe CEP 10, I need to get a specific value from an array with the find option in the JSX file. but JSX says find is not a function. how do I get a specific value from an array
Here is a pretty meaningless kindergarten style snippet but anyway:
var array = ["foo", "bar", "Alice", "Bob"];
var found = "";
var sample = prompt("Find for:");
var counter = 0;
while (counter<array.length) {
if (array[counter] == sample) {
found = sample;
break;
}
counter++;
}
if (found != "") {
alert("'" + found + "' was found in the array in position " + (counter+1));
} else {
alert("Nothing was found");
}
In:
Out:
Something like this can be done in various ways. Via indexOf() or includes(), etc. It depends on your task.
Related
I've tried to write a script for parsing a JSON file stored in the server and returning its pairs of key/values into list items containing the relevant attributes in colon-separated format.
I've attempted to do it by using native javascript commands. Although the file is parsed successfully and you can realize that by calling for distinct elements with reference numbers (eg. myObject.pets[1].animal or myObject.pets.length) the loop inside the code that is supposed to capture all items is not working.
Here is the code
<!DOCTYPE html>
<html>
<body>
<ul id="animals"></ul>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObject = JSON.parse(this.responseText);
var finalString = "";
for (i in myObject.pets.length) {
var currentItem = "<li>" + myObject.pets[i].animal + ": " + myObject.pets[i].name + "</li>";
var finalString = finalString.concat(currentItem);
}
document.getElementById("animals").innerHTML = finalString;
}
};
xmlhttp.open("GET", "animals.json", true);
xmlhttp.send();
</script>
</body>
</html>
The JSON file
>animals.json
{
"pets":[
{ "animal":"dog", "name":"Fido" },
{ "animal":"cat", "name":"Felix" },
{ "animal":"hamster", "name":"Lightning" }
]
}
and the expected outcome
<li>dog: Fido</li>
<li>cat: Felix</li>
<li>hamster: Lightning</li>
Javascript's for...in functionality loops through the properties of an object, it doesn't increment a variable up to a limit like you expect. Either use it as
for (let i in myObject.pets) which will give i the value of each key in the pets object (with indices in an array acting as keys in an object).
Or since this is a standard array you can do plenty of things with it. You could loop through it normally with for (let i = 0; i < myObject.pets.length; i++) but based on what you're trying to do I recommend reduce.
I've included a demo which uses reduce to get the finalString in a modern JS way. If you want to stick with your current function though, make sure you don't redefine finalString with var finalString in your loop which you are currently doing. My demo doesn't set the innerHTML of an element and instead writes it to the document, but you can do whatever you want with the finalString.
let apiResult = '{"pets":[{ "animal":"dog", "name":"Fido" }, { "animal":"cat", "name":"Felix" }, { "animal":"hamster", "name":"Lightning" } ] }';
let jsonResult = JSON.parse(apiResult);
let finalString = jsonResult.pets.reduce((total, current) => {
return total.concat("<li>" + current.animal + ": " + current.name + "</li>");
}, "");
document.write(finalString);
I really like #Matthew's answer. Here's a version using map instead of reduce, that makes the code more verbose, but I my opinion also easier to read.
const petsString = '{"pets": [{"animal": "dog", "name": "Fido"}, {"animal": "cat", "name": "Felix"}, {"animal": "hamster", "name": "Lightning"}]}'
const petsArray = JSON.parse(petsString).pets
const petsHtml = petsObject
.map(pet => `<li>${pet.animal}: ${pet.name}</li>`)
.join("")
document.write(petsHtml)
I am new to js and I don't understand much of codes and conditions in js.
My question is simple but I need someone to give me a good example if possible as I know what I need but it is getting hard to implement that in code.
This is my code with 2 arrays where the data is coming from.
blind_tmp = '';
for (i=0; i<#All of Blind Relationship Link.length; i++){
blind_tmp = blind_tmp + '<p>[**' + #All of Element Title[i] + '**](' + #All of Blind Relationship Link[i] + ')'
};
What simple needed is that. I want merge records that are duplicates printed.
for example: if Blind Relationship link is AF44 and after 6 elements this AF44 comes again so I want both to be written like 1.AF44,2.AF44
while now it is writing the elements how they come along
example:
AF11,AF22,AF33,AF44,AF55,AF66,AF77,AF44
so in this example you see two AF44
I want them to be written like this
AF11,AF22,AF33,AF44AF44,AF55,AF66,AF77
any help with a code example is appreciated.
The idea is to iterate through each element in the blindRelationshipLink and store those elements in a temporary array which will be used to check the number of occurrence of an array element.
var blindRelationshipLink = ['AF11','AF22','AF33','AF11','AF44','AF44','AF55','AF66','AF77','AF11','AF22','AF11'];
var arrTemp = [];
var p = '';
blindRelationshipLink.forEach(function(arr){
var count = 0;
arrTemp.forEach(function(a){
if(arr === a)
count++;
});
arrTemp.push(arr);
if(count){
count++;
arr= arr + '.' + count;
}
p = p + arr + ',';
});
alert(p);
You test by running the code snippet.
This approach is not best but it may serve your purpose.
Here is a snippet
var elemArray = ['AF11', 'AF22', 'AF33', 'AF44', 'AF55', 'AF66', 'AF77', 'AF44']; // Array of elements
//A new array which which will contain elements which pass our case
var finalArray = [];
elemArray.forEach(function(item) { // loop through main array
// Check if element is present or else push the element
if (finalArray.indexOf(item) == -1) {
finalArray.push(item);
} else {
// if element is there find the index
var getIndex = finalArray.indexOf(item);
// remove the element, else there will be duplicate
finalArray.splice(getIndex, 1);
//concate the matched element
var newElem = item + item;
// push the element in specfic index
finalArray[getIndex] = newElem;
}
})
console.log(finalArray)
Current drawback with this code is what will happen if there are multiple repeated item in the main array. For example presence of AF33 more than twice.
DEMO
I am using the twitter stream api. I am currently using follow & track parameters but the API combines them with an OR and I want to combine them with an AND. The only way logically to do this is to manually check that the tweet contains a userID# in my array of userIDs to follow and the tweet text contains a keyword from my array of keywords to track.
I have converted the tweet object and tweet.text object into a JSON string like this:
var tweetText = JSON.stringify(tweet.text);
var tweetObject = JSON.stringify(tweet);
I want an if statement like this:
if tweetObject == a value in tracked ids array && tweetText == a value in tracked words array
do the rest of my code
How can I achieve this? I tried to use .indexOf() but that takes only one parameter so I could say:
if(tweetObject.indexOf("12345678") > -1 && tweetText.indexOf("spotify") > -1) {
do my code
}
But this is NOT what I want, I want it to go through the array and see if tweetObject and tweetText contain any of the array elements and if so do the code
this is what I have:
// start twitter
t.stream(
"statuses/filter",
{follow: trackedHandles, track: trackedWords, lang: "en" },
function(stream) {
stream.on('data', function(tweet) {
//convert tweet.text& tweet.entities into two strings
var tweetText = JSON.stringify(tweet.text);
var userName = JSON.stringify(tweet.entities);
var tweetObject = JSON.stringify(tweet);
var flag = false;
for (var x = 0; x < trackedHandles.length; x++) {
//console.log(trackedHandles[x].toString());
var searchParam = tweetObject.indexOf(trackedHandles[x].toString());
if(searchParam != -1) {
flag = true;
//console.log(searchParam);
//console.log(trackedHandles[x].toString());
//incriment the keywords, and store the keywords as keys in redis (as they appear in feed)
for (var i = 0; i < trackedWords.length; i++) {
if(tweetText.indexOf(trackedWords[i]) > - 1) {
// incriments added value to the word
console.log(trackedWords[i]);
redisClient.incr(trackedWords[i]);
}
}
//if tweetText does not contains "RT" & "#", print tweet to console.
if(tweetText.indexOf("RT") == -1 && tweetText.indexOf("#") == -1) {
//console.log(tweetText + "\r\n ");
//console.log(screen_name + "\r\n ");
//console.log(tweet);
}
}
}
});
}
);
Please help guys, this is for my senior project for my undergrad degree. I have most of the app it self complete, I just need this one piece because What I am trying to accomplish is to only stream tweets from specific users based on specific keywords. If you can think of a more appropriate title for this please let me know. Thanks in advance for any help!
Use a for or forEach loop
var tweetObjArr= [1,2,3,4,5];
var tweetIds = [7,3]
var flag = false;
for (var i = 0; i < tweetIds .length; i++) {
if(tweetObjArr.indexOf(tweetIds [i]) != -1) {
flag=true;
break;
}
}
Might be you want jQuery.inArray function like
if(jQuery.inArray("12345678", tweetObject)!==-1)
I am currently trying to retrieve the corresponding dial_code by using the name which I am obtaining as a variable.
The application uses a map of the world. When the user hovers over a particular country, that country is obtained using 'getRegionName'. This is then used to alter the variable name. How can I use the variable name to retrieve the dial_code that it relates to?
JSON
var dialCodes = [
{"name":"China","dial_code":"+86","code":"CN"},
{"name":"Afghanistan","dial_code":"+93","code":"AF"}
];
The following code runs on mouse hover of a country
var countryName = map.getRegionName(code);
label.html(name + ' (' + code.toString() + ')<br>' + dialCodes[0][countryName].dial_code);
This code doesn't work correctly. The dialCodes[0][countryName].dial_code is the part that is causing the error, but I'm not sure how to correctly refer to the corresponding key/value pair
If you have to support old browsers:
Loop over the entries in the array and compare to the given name:
var dialCode;
for(var i = 0; i < dialCodes.length; i++) {
if(dialCodes[i].name === countryName) {
dialCode = dialCodes[i].dial_code;
break;
}
}
label.html(countryName + ' (' + dialCode + ')');
If you browser support Array.prototype.filter:
dialCodes.filter(function(e) { return e.name === 'China' })[0].dial_code
If you have control over it, I recommend making your object more like a dictionary, for example if you are always looking up by the code (CN or AF) you could avoid looping if you did this:
var dialCodes = {
CN: { "name":"China","dial_code":"+86","code":"CN" },
AF: {"name":"Afghanistan","dial_code":"+93","code":"AF"}
};
var code = dialCodes.CN.dial_code;
Or
var myCode = 'CN'; // for example
var code = dialCodes[myCode].dial_code;
Since it's an array you can use filter to extract the data you need.
function getData(type, val) {
return dialCodes.filter(function (el) {
return el[type] === val;
})[0];
}
getData('code', 'CN').dial_code; // +86
I'm trying to sort my javascript popuplated select list and ive searched through all the other posts on this site but i cant get it to work...
here is my javascript that auto populates the select list from an data in an SQL db:
for (clientKey in clientProjectsHash) {
//alert("client:" + clientKey + ", name: " + clientProjectsHash[clientKey].name);
clientSelect.options[clientSelect.options.length] = new Option(clientProjectsHash[clientKey].name, clientKey);
if(selectedClientId == undefined || selectedClientId == 0) {
if(clientKey > 0) {
selectedClientId=clientKey;
}
}
ive tried to add:
clientProjectsHash.sort(); to the top but it doesn't work... anyone help is appreciated!
this is my other function to get the first client ID from database:
function getInitialClient() {
for (clientKey in clientProjectsHash) {
if(clientKey > 0) {
return clientKey;
}
}
}
Here we go.
You want to sort an object's enumerable keys by their values.
You can use Object.keys to get the enumerable properties of an object.
Then, you can use Array.map to convert each key, to its value in the object.
(That link has a shim for older browsers in both of those)
Then you can call the normal sort function on them.
Example
Let's say your object is something like
var obj = {
"a":"Hello",
"b":"World",
"c":"AAAA",
"d":"ZZZZ",
};
var a = Object.keys(obj).map(function(elem){ // Get the keys, and map them
return obj[elem]; // to their value
}).sort(); // then sort
Here is a working fiddle
Your case:
In your case, this would be something like
var sortedValues = Object.keys(clientProjectsHash).map(function(elem){ // Get the keys, and map them
return clientProjectsHash[elem]; // to their value
}).sort();
Try something like this:
var list = [];
for(key in clientProjectsHash)
list.push(key);
list.sort();
for(var i=0; i<list.length; i++)
{
clientSelect.options[clientSelect.options.length] = new Option(clientProjectsHash[list[i]].name, clientKey);
if(selectedClientId == undefined || selectedClientId == 0) {
if(clientKey > 0) {
selectedClientId=clientKey;
}
}
}