JS select value of multidimentional objects - javascript

So, I have following js setup:
var NAMES = [];
function INFO(id,first,middle,last){
var newMap = {};
newMap[id] = [first, middle, last];
return newMap ;
}
Then,
Then I get following result:
I am trying to select the individual value like below:
For example, I want to select "Sean" under "185"
var f = '185';
select_data = NAMES[f][0];
But I keep getting an error saying that "0" is not an identifier.
I am bit confused. Can someone help me out how to select the value properly?

You need to get the object inside the array first, so it should be as follows
var f = '185';
select_data = NAMES[0][f][0];
// -------^----- getting first element from array, which is the object

Related

Split php varibale with JS into array

I have tried everything and I can not split a PHP variable into two parts so I can insert them into two input fields. I have read numerous topics here and I don't see the problem...
This peace of code gives me a result that php variable is inserted into a wanted filed.
Lets say the PHP variable is data1-data2:
document.hiderad.selectstate.onchange = updateText;
function updateText() {
var str = document.hiderad.selectstate;
document.hiderad.opis.value = str.value;
}
Code above inserted data1-data2 into wanted HTML input.
And soon as i try to split it i get undefined warning. I have tried 7 different things to approach this problem so i want even list all the versions I tried. Can someone please help?
document.hiderad.selectstate.onchange = updateText;
function updateText() {
var str = document.hiderad.selectstate;
var array = str.toString().split('-');
a = array[0], b = array[1];
document.hiderad.opis.value = a.value;
document.hiderad.iznos.value = b.value;
}
Code above gives me b undefined if i remove last line i get a undefined.
You shouldn't be using a.value and b.value, that's for getting the value of an input field, not a string. You should use that to get the value of the selectstate input.
Also, always declare local variables unless you have a specific reason to assign global variables.
function updateText() {
var str = document.hiderad.selectstate;
var array = str.value.split('-');
var a = array[0], b = array[1];
document.hiderad.opis.value = a;
document.hiderad.iznos.value = b;
}

Array not giving expected answer using split function

In this code console.log (name[i]) results in first character of split string(i.e. c ,s,t) but i want name separate like chris. and its giving the expected result on MDN but not on console on js.
var char=['chris:2255655','sarrah:5456454','taur:5655226'];
var name=new Array();
for(var i=0;i<char.length;++i){
name=char[i].split(':');
console.log(name[i]);
}
Your code should look like
var char=['chris:2255655','sarrah:5456454','taur:5655226'];
for(var i=0;i<char.length;++i){
var w = char[i].split(":");
console.log(w[0]);
}
Please check my snippet. It seems that your split was not resulting an array but a string. So you were getting only the first symbol
You can simply do:
var char=['chris:2255655','sarrah:5456454','taur:5655226']
// As array
console.log(char.map(x => x.split(':')[0]))
// As a string
console.log(...char.map(x => x.split(':')[0]))
We are using map to go through each of the strings and split on :.
Since split gives us an array we take the 0 index which contains the name. Since Map returns an array you can either leave as is or destructure it with ... to get its contents.
You can do like this.
const char=['chris:2255655','sarrah:5456454','taur:5655226'];
const name= [];
for(let i=0;i<char.length;i++){
let val =char[i].split(':');
name.push(val[0]);
console.log(name[i]);
}
Since you know the position of your selection you can assign directly to a variable:
var char = ['chris:2255655', 'sarrah:5456454', 'taur:5655226']
var names = char.map(item => {
var [name] = item.split(':'); // <- select only first index
// var [name, id] = item.split(':'); // <- select first and second index
// var [name, ...rest] = item.split(':'); // <- select first and rest of the elements
// var [name,] = item.split(':'); // <- select first and skip next element index using ","
return name;
})
console.log(names);

Json array getting first data

I have an array which I declared as var myclinicsID = new Array(); and now, I push some data in it,when I alert it using alert(JSON.stringify(myclinicsID)) it gives me output of ["1","2","3","4"]
Now I want to use this for my function and when I look at in console, it gives me undefined, am I doing correct by my code :
getbarSeriesData(myclinicsID[0]['clinic_id'],data[i]['datemonths']);
I want to get myclinicsID first data element which is the value is 1
myclinicsID[0]['clinic_id']
Should be
myclinicsID[0]
All you need the array index. When you say myclinicsID[0]['clinic_id'], that is trying to get the clinic_id property of "1" which is obvious undefined.
Why myclinicsID[0]['clinic_id'] ? As there is nothing like clinic_id in your array.
Your array is single dimensional array. Hence, you can directly access the first element from an array using myclinicsID[0].
DEMO
var myclinicsID = new Array();
myclinicsID[0] = 1;
myclinicsID[1] = 2;
myclinicsID[2] = 3;
myclinicsID[3] = 4;
function getbarSeriesData(clientID) {
console.log(clientID);
alert(clientID);
}
getbarSeriesData(myclinicsID[0]);

Underscore.js `filter` not working

I have the following code snippet I use to choose which suburbs from a list the user has selected (with irrelevant code omitted):
var allSuburbsList = new Array([{"SuburbID":1,"SuburbAreaID":3,"SuburbName":"Alberante","SuburbActive":true,"Area":null,"Agents":[]},{"SuburbID":4,"SuburbAreaID":3,"SuburbName":"Alberton North","SuburbActive":true,"Area":null,"Agents":[]}]);
var a3burbs = _.filter(allSuburbsList, function(s) { return s.SuburbAreaID === 3; });
// 3 is a test value. All the test suburbs so far fall under area no. 3.
With this filter, a3burbs comes out as an empty array, []. If I cheat and make the filter:
var a3burbs = _.filter(allSuburbsList, function(s) { return true; });
then a3bubrs comes out an exact copy of allSuburbsList, with all suburbs included. What could I be doing wrong? I'm using the same syntax as indicated on the Underscore.js home page.
Btw, would the way I populate allSuburbsList from a viewmodel array property have anything to do with this:
var allSuburbsList = new Array(#Html.Raw(JsonConvert.SerializeObject(Model.AllSuburbs)));
Just for interest, my first attempt was the hideous code below, but it worked:
var a3burbs = [];
#{for (var i = 0; i < Model.AllSuburbs.Length; i++) {
#:if (allSuburbsList[#i].SuburbAreaID === 3) {
#:a3burbs.push(allSuburbsList[#i]);
};
};
You're creating a new array and passing in an array.
Change it to
var allSuburbsList = [{"SuburbID":1,"SuburbAreaID":3,"SuburbName":"Alberante","SuburbActive":true,"Area":null,"Agents":[]},{"SuburbID":4,"SuburbAreaID":3,"SuburbName":"Alberton North","SuburbActive":true,"Area":null,"Agents":[]}];
Using new Array([{}]), you are creating an array inside another array. Just instantiate that without new Array()

dynamic object properties javascript

Having issues with this code block:
var name = "";
var nutrients = {};
var tds = document.getElementById('data').getElementsByTagName('td');
name = tds[0].innerHTML;
nutrients[name].val = tds[1].innerHTML;
alert(nutrients.Energy.val);
If I take out the .val on both lines, the code works. I'm trying to dynamically create the "
nutrients" abject by extracting information from a table. "Energy", and all 50 of nutrient names must have a "value" and a "unit" property. Eventually this will be a loop.
Thanks for any help
When trying to assign
nutrients[name].val = tds[1].innerHTML;
the nutrients object is still empty, and nutrients["Energy"] (or whatever) will be undefined; throwing an exception when beeing assigned a property. Instead, use
nutrients[name] = {
val: tds[1].innerHTML
};

Categories

Resources