How to search array keys in JavaScript/jQuery using indexOf - javascript

I have an array members. This array has a name as the index (e.g. "John Smith") and an array with "degree" and "id", like so:
I have a search that fires on keyup action. It is supposed to search through the member names (the index) and then output the name of any matching members to the console:
function memberSearch(){
var $input = $("#guestsearch>input");
var val = $input.val();
console.log(val);
$.each(members, function(i,v){
if(i.indexOf(val)>-1){
console.log(members[i]);
}
})
}
However, this doesn't output anything except the search value val. Even if the $.each function is just console.log(i), nothing outputs.
If I manually type console.log(members) into console, the screenshot from above is the result.
members is populated by this segment of a function:
$.each(json.response.data[0].members, function(i,v){
var m = json.response.data[0].members[i];
var name = m.name;
if(name.typeof!=="undefined"&&name!=""&&name!=null&&name.length>0){
members[name] = [];
members[name]["degree"] = m.degree;
members[name]["id"] = m.id;
}
})
How can I make this search work?

If members is an object, which it looks like with the key/value pairs, you can use Object.keys(objVariable) to get the keys of an object to loop over and do your comparison/regex logic on.
Object.keys(members).forEach(function(name){
if (/* logic to match on name */) {
console.log(members[name]);
}
});
Otherwise if members is an array containing those objects...
var matchingUsers = members.filter(function(){
var username = Object.keys(this)[0];
return (/* match username to whatever */);
});
Then matchingUsers would be an array containing all the users that passed your criteria.

Related

How to fetch values from json array object without using object key name javascript?

Json Array Object
Through Ajax I will get dynamic data which is not constant or similar data based on query data will change. But I want to display charts so I used chartjs where I need to pass array data. So I tried below code but whenever data changes that code will break.
I cannot paste complete JSON file so after parsing it looks like this
[{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
You can use Object.keys and specify the position number to get that value
var valueOne =[];
var valueTwo = [];
jsonData.forEach(function(e){
valueOne.push(e[Object.keys(e)[1]]);
valueTwo.push(e[Object.keys(e)[2]]);
})
It seems like what you're trying to do is conditionally populate an array based the data you are receiving. One solution might be for you to use a variable who's value is based on whether the value or price property exist on the object. For example, in your forEach loop:
const valueOne = [];
jsonData.forEach((e) => {
const val = typeof e.value !== undefined ? e.value : e.average;
valueOne.push(val);
})
In your jsonData.forEach loop you can test existence of element by using something like:
if (e['volume']===undefined) {
valueone.push(e.price);
} else {
valueone.push(e.volume);
}
And similar for valuetwo...
You could create an object with the keys of your first array element, and values corresponding to the arrays you are after:
var data = [{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
var splitArrays = Object.keys(data[0]).reduce((o, e) => {
o[e] = data.map(el => el[e]);
return o;
}, {});
// show the whole object
console.log(splitArrays);
// show the individual arrays
console.log("brand");
console.log(splitArrays.brand);
console.log("volume");
console.log(splitArrays.volume);
// etc

Using the search function in Google scripts array

I am trying to create a function to search for regex in a cell and return a given value if the result is found.
The function works per cell, but I can't get it to work by array applying the function to B1:B10 rather than just B10. I want it to work as array to speed up the function.
I am receiving this error message when I apply pagetype function to an array.
TypeError: Cannot find function search in object yfhhh. (line 13).
I understand that I need to edit the function somehow to have it working on a range of cells but am not sure how...this is my code:
function pageType(string) {
if (string.map) // Test whether input is an array.
return string.map(page); // Recurse over array if so.
else {
return page(string);
}
}
function page(url) {
var productpage = /.*\.html.*/
var homepage = /^http:\/\/www\.domain.com\/$/
var categorypage = /^http:\/\/www\.domain\.com\/.*/
if (url.search(categorypage) > -1)
return "Category Page";
if (url.search(productpage) > -1)
return "Product Page";
if (url.search(homepage) > -1)
return "Homepage";
else
return "Brand Page";
}
There is no search() method for an array. An array is a sub category of the broader category of object. Then there is a JSON object, which is an object.
object - includes
JSON object {'key':'value'}
Array ['element1','element2']
An array is a sub category of an object. It's kind of confusing to call an array an object. But that is what the error message is doing.
Because you are using RegEx, you can't use indexOf(), which is a method of both a string and an array.
You could covert the array to a string:
var myArray = myArray.toString();
and then search the string for the match. In your case, you are returning a pre-defined value, so that should work. It doesn't seem that you need to extract something from the array after a match is found. Which would require more processing.
if (typeof url === 'object') {//If data is an array
url = url.toString();
}

Split an object into array of objects based on a condition in JavaScript

How to split an object into array of objects based on a condition.
oldObject = {"Chicago, IL:Myrtle Beach, SC": 0.005340186908091907,
"Portsmouth, NH:Rock Hill, SC": 0.0063224791225441205,
"Columbia, SC:Laconia, NH": 0.006360767389277389,
"Council Bluffs, IA:Derry, NH": 0.0016636141225441225}
Above is the given sample object. I want to make an array of objects like this,
newArray = [{"city":"Chicago", "similarTo":"Myrtle"},
{"city":"Portsmouth", "similarTo":"Rock Hill"},
{"city":"Columbia", "similarTo":"Laconia"},
{"city":"Council Bluffs", "similarTo":"Derry"}]
I have been scratching my head with this for a while now. How can I get the above array(newArray)?
Here is a bunch of code you can try.
1) Iterate over oldObject and get the name of the property.
2) Split that name into an array based on the ":" character, since it separates the cities
3) Go over that new array, splitting it on the "," character (so as not to get the states).
4) Put the values into the newObject, based on whether it's the first or second part of the original property name.
5) Push that newObject, now with items, into a newArray.
Basically, this parses apart the name and does some array splitting to get at the right values. Hope it helps and helps you understand too.
var oldObject = {"Chicago, IL:Myrtle Beach, SC": 0.005340186908091907,
"Portsmouth, NH:Rock Hill, SC": 0.0063224791225441205,
"Columbia, SC:Laconia, NH": 0.006360767389277389,
"Council Bluffs, IA:Derry, NH": 0.0016636141225441225};
var newArray = [];
for (object in oldObject) {
var thisObjectName = object;
var thisObjectAsArray = thisObjectName.split(':');
var newObject = {
'city': '',
'similar_to': ''
};
thisObjectAsArray.forEach(function(element,index,array) {
var thisObjectNameAsArray = element.split(',');
var thisObjectNameCity = thisObjectNameAsArray[0];
if(index===0) {
newObject.city = thisObjectNameCity;
} else if(index===1) {
newObject.similar_to = thisObjectNameCity;
}
});
newArray.push(newObject);
}
console.log(newArray);
PS: to test, run the above code and check your Developer Tools console to see the new array output.

How would I go about using a multidimensional array variable in javascript

Hi there before I start I did try looking through the search about writing variables so if this has been asked and answered then I do apologise but this is baffling me ....
So here goes ..
example of what I am talking about
var i = e[ab]
var n = e[cd][ef]
var t = e[cd][gh]
I know that when I want var i I can put e.ab but how would I go about writing var n and var t
So assuming your object looks like this (based on your description, it sounds like you want to access an object which is the property of another object), and you want to access them through the indexer properties (which would be a property of a property).
var e = {
ab : "variableOne",
cd : {ef:"ef object"},
gh : {ij:"ij object"},
}
var i = e["ab"]
//if these are properties, then you need to add quotes around them
//to access a property through the indexer, you need a string.
var n = e["cd"]["ef"]
var t = e["gh"]["ij"]
console.log(i);
console.log(n);
console.log(t);
console.log("this does the same thing:")
console.log(e.ab);
console.log(e.cd.ef);
console.log(e.gh.if);
In your example the object would look like
//e is the parameter, but I show it as a variable to show
// it's relation to the object in this example.
e = {
now_playing: {artist:"Bob Seger"; track:"Turn the Page"}}
}
this is different than an array of arrays:
var arr = [
['foo','charlie'],
['yip', 'steve'],
['what', 'bob', 'jane'],
];
console.log(arr[0][0]); //foo
console.log(arr[0][1]); //charlie
console.log(arr[1][0]); //yip
console.log(arr[1][1]); //steve
console.log(arr[2][2]); //jane
https://jsfiddle.net/joo9wfxt/2/
EDIT:
Based on the JSON provided, it looks like parameter e in the function is assigned the value of the item in the array. With your code:
this line will display: "Rock you like a hurricane - Nontas Tzivenis"
$(".song_title .current_show span").html(e.title);
and this line will display: "Rascal Flatts - Life is a Highway".
$(".song_title .current_song span").html(e.np);
If it's not displaying you might want to double check your JQuery selectors. This ".song_title .current_song span" is selecting it by the classes on the element.
I think you are in need of a bit of a refresher on basic JavaScript syntax. Here's how you can assign an "empty object" to a variable, then start to assign values to it's properties:
e = {}
e.ab = {}
e.cd = {}
e.cd.ef = "data"
or you can use the associative array syntax for property access:
e = {}
e["ab"] = {}
e["cd"] = {}
e["cd"]["ef"] = "data"
You see the latter is using the object e like a two-deep associative array. Is that what you are looking to do?
JavaScript is not strongly typed. So an Array "a" could contain objects of different types inside.
var a = [ "a value", [1, 2, 3], function(){ return 5 + 2;}];
var result = a[0]; //get the first item in my array: "a value"
var resultOfIndexedProperty = a[1][0]; //Get the first item of the second item: 1
var resultOfFunc = a[2](); //store the result of the function that is the third item of my array: 7
Hope this helps a little.

OOP get this key value of object array

So close to nailing this but falling at the last hurdle... Need some clarification.
Basically, I want to load in the array value of a key in a given object as a variable, if other variable strings match.
Perhaps it's better if I give it some context:
js:
var ArraysObject = {
"new" : [
"http://productPageBanners/UK/2new/c0bkn201001u0000.jpg",
"http://productPageBanners/UK/2new/h0ihd60100000001.jpg",
"http://productPageBanners/UK/2new/l0flj20100000001.jpg",
"http://productPageBanners/UK/2new/m0lrt60100000001.jpg",
"http://productPageBanners/UK/2new/p0gps50106000001.jpg"
],
"knives" : [
"http://productPageBanners/UK/3aknives/c0bkn201001u0000.jpg",
"http://productPageBanners/UK/3aknives/n01pl20100000001.jpg"
]
};
var url = jQuery(location).attr('href'); // get the current url, outputs URL
var icatRef = url.split("/")[4]; // capture the icatRef from url, outputs ==>"knives"
// Get properties on the object ArraysObject as an array
var icatTitlesInObject = Object.keys(ArraysObject); // outputs the keys in object, i.e ==> ["new","knives"]
Then I want to check that if the indexOf that array is equal to the icatRef (pulled from the URL), then create a new variable which stores the relevant array from the correct key.
Something like:
if (icatsArray.indexOf() == icatRef) {
var currentarraytorandomise = ArraysObject.keys.this};
// if "knives" is the icatRef then currentarraytorandomise ==> [
// "http://productPageBanners/UK/3aknives/c0bkn201001u0000.jpg",
// "http://productPageBanners/UK/3aknives/n01pl20100000001.jpg"
// ]
However that last bit is wrong because currentarraytorandomise is undefined.
I hope that's clear! Quite new to OOP.
You're using indexOf incorrectly, try something like this:
var currentarraytorandomise, index = icatsArray.indexOf(icatRef);
if (index >= 0) {
currentarraytorandomise = ArraysObject[icatsArray[index]];
}
But you could just try to get the array directly:
ArraysObject[icatRef]
Without extracting keys or anything. If icatRef doesn't exist, you'll get undefined.

Categories