Getting two values from a Vue <select> #change event - html
I have a drop-down <select> element that uses an array with key:value pairs. I'd like for the dropdown to only display values, but upon selection have the #change pass on both the value and the key.
<select
#change="
formChanged(
$event,
$event.target.selectedIndex,
$event.target.value,
$event.target.key
)
"
name="selectForm"
id="selectForm"
required
>
<option
v-for="(option, id) in getFormSelectArray()"
:key="id" :value="option"
>
{{ option }}
</option>
</select>
My function called through #change:
formChanged(event, selectedIndex, value, id): void {
console.log(
'Form Selection Changed: ' + event + ' ' + selectedIndex + ' ' + value, + ' ' + id
);
}
My data array generating function:
public getFormSelectArray() {
// Mapping IDs to Names
const names = 'a, b, c';
const ids = '123, 456, 789';
let i;
let currentKey;
let currentVal;
const result = {}
for (i = 0; i < ids.split(',').length; i++) {
currentKey = ids.split(',')[i];
currentVal = names.split(',')[i];
result[currentKey] = currentVal;
}
for (const key in result) {
const value = result[key];
}
return result;
}
My output:
Form Selection Changed: [object Event] 0 a NaN
How do I output the ID of 123 instead of NaN?
I think you should use #input instead of #change.
Related
How to display the second value of array dynamically
How would one generically pull the second item under the forecast array without defining the specific 'date' value? Currently, I have to specify the date like "2020-01-27" in order to pull the data. I tried these but they are not working... {{ forecast.value[1].hourly[0].weather_code }} {{ forecast[1].hourly[0].weather_code }} Here's the data: {"request":{"type":"Zipcode","query":"90210","language":"en","unit":"f"},"location":{"name":"Beverly Hills","country":"USA","region":"California","lat":"34.087","lon":"-118.412","timezone_id":"America\/Los_Angeles","localtime":"2021-01-26 14:07","localtime_epoch":1611670020,"utc_offset":"-8.0"},"current":{"observation_time":"10:07 PM","temperature":54,"weather_code":113,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png"],"weather_descriptions":["Sunny"],"wind_speed":7,"wind_degree":190,"wind_dir":"S","pressure":1016,"precip":0,"humidity":26,"cloudcover":0,"feelslike":54,"uv_index":4,"visibility":10,"is_day":"yes"},"forecast":{"2021-01-26":{"date":"2021-01-26","date_epoch":1611619200,"astro":{"sunrise":"06:54 AM","sunset":"05:19 PM","moonrise":"03:22 PM","moonset":"05:25 AM","moon_phase":"Full Moon","moon_illumination":90},"mintemp":45,"maxtemp":59,"avgtemp":52,"totalsnow":0,"sunhour":10.7,"uv_index":3,"hourly":[{"time":"0","temperature":46,"wind_speed":9,"wind_degree":305,"wind_dir":"NW","weather_code":116,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0004_black_low_cloud.png"],"weather_descriptions":["Partly cloudy"],"precip":0,"humidity":47,"visibility":6,"pressure":1009,"cloudcover":7,"heatindex":46,"dewpoint":27,"windchill":43,"windgust":13,"feelslike":43,"chanceofrain":0,"chanceofremdry":85,"chanceofwindy":0,"chanceofovercast":43,"chanceofsunshine":84,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":1},{"time":"300","temperature":46,"wind_speed":7,"wind_degree":306,"wind_dir":"NW","weather_code":113,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0008_clear_sky_night.png"],"weather_descriptions":["Clear"],"precip":0,"humidity":50,"visibility":6,"pressure":1010,"cloudcover":2,"heatindex":46,"dewpoint":28,"windchill":43,"windgust":9,"feelslike":43,"chanceofrain":0,"chanceofremdry":87,"chanceofwindy":0,"chanceofovercast":25,"chanceofsunshine":82,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":1},{"time":"600","temperature":46,"wind_speed":6,"wind_degree":329,"wind_dir":"NNW","weather_code":116,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0004_black_low_cloud.png"],"weather_descriptions":["Partly cloudy"],"precip":0,"humidity":50,"visibility":6,"pressure":1012,"cloudcover":1,"heatindex":46,"dewpoint":28,"windchill":43,"windgust":7,"feelslike":43,"chanceofrain":0,"chanceofremdry":89,"chanceofwindy":0,"chanceofovercast":11,"chanceofsunshine":86,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":1},{"time":"900","temperature":48,"wind_speed":5,"wind_degree":340,"wind_dir":"NNW","weather_code":113,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png"],"weather_descriptions":["Sunny"],"precip":0,"humidity":45,"visibility":6,"pressure":1015,"cloudcover":2,"heatindex":48,"dewpoint":27,"windchill":46,"windgust":6,"feelslike":46,"chanceofrain":0,"chanceofremdry":87,"chanceofwindy":0,"chanceofovercast":23,"chanceofsunshine":86,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":3},{"time":"1200","temperature":55,"wind_speed":4,"wind_degree":294,"wind_dir":"WNW","weather_code":116,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0002_sunny_intervals.png"],"weather_descriptions":["Partly cloudy"],"precip":0,"humidity":33,"visibility":6,"pressure":1016,"cloudcover":1,"heatindex":55,"dewpoint":27,"windchill":55,"windgust":5,"feelslike":55,"chanceofrain":0,"chanceofremdry":91,"chanceofwindy":0,"chanceofovercast":12,"chanceofsunshine":87,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":4},{"time":"1500","temperature":57,"wind_speed":5,"wind_degree":221,"wind_dir":"SW","weather_code":116,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0002_sunny_intervals.png"],"weather_descriptions":["Partly cloudy"],"precip":0,"humidity":31,"visibility":6,"pressure":1016,"cloudcover":3,"heatindex":57,"dewpoint":28,"windchill":57,"windgust":6,"feelslike":57,"chanceofrain":0,"chanceofremdry":86,"chanceofwindy":0,"chanceofovercast":35,"chanceofsunshine":78,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":4},{"time":"1800","temperature":54,"wind_speed":6,"wind_degree":204,"wind_dir":"SSW","weather_code":116,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0004_black_low_cloud.png"],"weather_descriptions":["Partly cloudy"],"precip":0,"humidity":36,"visibility":6,"pressure":1017,"cloudcover":12,"heatindex":54,"dewpoint":28,"windchill":54,"windgust":6,"feelslike":54,"chanceofrain":0,"chanceofremdry":86,"chanceofwindy":0,"chanceofovercast":38,"chanceofsunshine":85,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":1},{"time":"2100","temperature":52,"wind_speed":4,"wind_degree":159,"wind_dir":"SSE","weather_code":116,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0004_black_low_cloud.png"],"weather_descriptions":["Partly cloudy"],"precip":0,"humidity":40,"visibility":6,"pressure":1019,"cloudcover":36,"heatindex":52,"dewpoint":28,"windchill":50,"windgust":5,"feelslike":50,"chanceofrain":0,"chanceofremdry":87,"chanceofwindy":0,"chanceofovercast":40,"chanceofsunshine":80,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":1}]}}}
Try this: const obj = {"request":{"type":"Zipcode","query":"90210","language":"en","unit":"f"},"location":{"name":"Beverly Hills","country":"USA","region":"California","lat":"34.087","lon":"-118.412","timezone_id":"America\/Los_Angeles","localtime":"2021-01-26 14:07","localtime_epoch":1611670020,"utc_offset":"-8.0"},"current":{"observation_time":"10:07 PM","temperature":54,"weather_code":113,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png"],"weather_descriptions":["Sunny"],"wind_speed":7,"wind_degree":190,"wind_dir":"S","pressure":1016,"precip":0,"humidity":26,"cloudcover":0,"feelslike":54,"uv_index":4,"visibility":10,"is_day":"yes"},"forecast":{"2021-01-26":{"date":"2021-01-26","date_epoch":1611619200,"astro":{"sunrise":"06:54 AM","sunset":"05:19 PM","moonrise":"03:22 PM","moonset":"05:25 AM","moon_phase":"Full Moon","moon_illumination":90},"mintemp":45,"maxtemp":59,"avgtemp":52,"totalsnow":0,"sunhour":10.7,"uv_index":3,"hourly":[{"time":"0","temperature":46,"wind_speed":9,"wind_degree":305,"wind_dir":"NW","weather_code":116,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0004_black_low_cloud.png"],"weather_descriptions":["Partly cloudy"],"precip":0,"humidity":47,"visibility":6,"pressure":1009,"cloudcover":7,"heatindex":46,"dewpoint":27,"windchill":43,"windgust":13,"feelslike":43,"chanceofrain":0,"chanceofremdry":85,"chanceofwindy":0,"chanceofovercast":43,"chanceofsunshine":84,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":1},{"time":"300","temperature":46,"wind_speed":7,"wind_degree":306,"wind_dir":"NW","weather_code":113,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0008_clear_sky_night.png"],"weather_descriptions":["Clear"],"precip":0,"humidity":50,"visibility":6,"pressure":1010,"cloudcover":2,"heatindex":46,"dewpoint":28,"windchill":43,"windgust":9,"feelslike":43,"chanceofrain":0,"chanceofremdry":87,"chanceofwindy":0,"chanceofovercast":25,"chanceofsunshine":82,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":1},{"time":"600","temperature":46,"wind_speed":6,"wind_degree":329,"wind_dir":"NNW","weather_code":116,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0004_black_low_cloud.png"],"weather_descriptions":["Partly cloudy"],"precip":0,"humidity":50,"visibility":6,"pressure":1012,"cloudcover":1,"heatindex":46,"dewpoint":28,"windchill":43,"windgust":7,"feelslike":43,"chanceofrain":0,"chanceofremdry":89,"chanceofwindy":0,"chanceofovercast":11,"chanceofsunshine":86,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":1},{"time":"900","temperature":48,"wind_speed":5,"wind_degree":340,"wind_dir":"NNW","weather_code":113,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png"],"weather_descriptions":["Sunny"],"precip":0,"humidity":45,"visibility":6,"pressure":1015,"cloudcover":2,"heatindex":48,"dewpoint":27,"windchill":46,"windgust":6,"feelslike":46,"chanceofrain":0,"chanceofremdry":87,"chanceofwindy":0,"chanceofovercast":23,"chanceofsunshine":86,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":3},{"time":"1200","temperature":55,"wind_speed":4,"wind_degree":294,"wind_dir":"WNW","weather_code":116,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0002_sunny_intervals.png"],"weather_descriptions":["Partly cloudy"],"precip":0,"humidity":33,"visibility":6,"pressure":1016,"cloudcover":1,"heatindex":55,"dewpoint":27,"windchill":55,"windgust":5,"feelslike":55,"chanceofrain":0,"chanceofremdry":91,"chanceofwindy":0,"chanceofovercast":12,"chanceofsunshine":87,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":4},{"time":"1500","temperature":57,"wind_speed":5,"wind_degree":221,"wind_dir":"SW","weather_code":116,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0002_sunny_intervals.png"],"weather_descriptions":["Partly cloudy"],"precip":0,"humidity":31,"visibility":6,"pressure":1016,"cloudcover":3,"heatindex":57,"dewpoint":28,"windchill":57,"windgust":6,"feelslike":57,"chanceofrain":0,"chanceofremdry":86,"chanceofwindy":0,"chanceofovercast":35,"chanceofsunshine":78,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":4},{"time":"1800","temperature":54,"wind_speed":6,"wind_degree":204,"wind_dir":"SSW","weather_code":116,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0004_black_low_cloud.png"],"weather_descriptions":["Partly cloudy"],"precip":0,"humidity":36,"visibility":6,"pressure":1017,"cloudcover":12,"heatindex":54,"dewpoint":28,"windchill":54,"windgust":6,"feelslike":54,"chanceofrain":0,"chanceofremdry":86,"chanceofwindy":0,"chanceofovercast":38,"chanceofsunshine":85,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":1},{"time":"2100","temperature":52,"wind_speed":4,"wind_degree":159,"wind_dir":"SSE","weather_code":116,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0004_black_low_cloud.png"],"weather_descriptions":["Partly cloudy"],"precip":0,"humidity":40,"visibility":6,"pressure":1019,"cloudcover":36,"heatindex":52,"dewpoint":28,"windchill":50,"windgust":5,"feelslike":50,"chanceofrain":0,"chanceofremdry":87,"chanceofwindy":0,"chanceofovercast":40,"chanceofsunshine":80,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":1}]}}} function getWeatherCode(obj) { let val; Object.keys(obj).forEach((e) => { if(e == 'forecast'){ val = obj[e][formatDate()]['hourly'][1]['weather_code']; } }); return val; } function formatDate() { var d = new Date('2021-01-26'), month = '' + (d.getMonth() + 1), day = '' + d.getDate(), year = d.getFullYear(); if (month.length < 2) month = '0' + month; if (day.length < 2) day = '0' + day; return [year, month, day].join('-'); } let a = getWeatherCode(obj); console.log(a); I harcoded the date but you delete the date and take current date like the following var d = new Date() I think this will help for you Just use {{ getWeatherCode(obj) }}
Like that: return Object.entries(forecast)[0][1]; Object.entries transforms the object to an array of key-value pairs, [0] grabs the first one, and then [1] grabs value ([0] would be the key).
All I can think of is something like this const obj = {"request":{"type":"Zipcode","query":"90210","language":"en","unit":"f"},"location":{"name":"Beverly Hills","country":"USA","region":"California","lat":"34.087","lon":"-118.412","timezone_id":"America\/Los_Angeles","localtime":"2021-01-26 14:07","localtime_epoch":1611670020,"utc_offset":"-8.0"},"current":{"observation_time":"10:07 PM","temperature":54,"weather_code":113,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png"],"weather_descriptions":["Sunny"],"wind_speed":7,"wind_degree":190,"wind_dir":"S","pressure":1016,"precip":0,"humidity":26,"cloudcover":0,"feelslike":54,"uv_index":4,"visibility":10,"is_day":"yes"},"forecast":{"2021-01-26":{"date":"2021-01-26","date_epoch":1611619200,"astro":{"sunrise":"06:54 AM","sunset":"05:19 PM","moonrise":"03:22 PM","moonset":"05:25 AM","moon_phase":"Full Moon","moon_illumination":90},"mintemp":45,"maxtemp":59,"avgtemp":52,"totalsnow":0,"sunhour":10.7,"uv_index":3,"hourly":[{"time":"0","temperature":46,"wind_speed":9,"wind_degree":305,"wind_dir":"NW","weather_code":116,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0004_black_low_cloud.png"],"weather_descriptions":["Partly cloudy"],"precip":0,"humidity":47,"visibility":6,"pressure":1009,"cloudcover":7,"heatindex":46,"dewpoint":27,"windchill":43,"windgust":13,"feelslike":43,"chanceofrain":0,"chanceofremdry":85,"chanceofwindy":0,"chanceofovercast":43,"chanceofsunshine":84,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":1},{"time":"300","temperature":46,"wind_speed":7,"wind_degree":306,"wind_dir":"NW","weather_code":113,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0008_clear_sky_night.png"],"weather_descriptions":["Clear"],"precip":0,"humidity":50,"visibility":6,"pressure":1010,"cloudcover":2,"heatindex":46,"dewpoint":28,"windchill":43,"windgust":9,"feelslike":43,"chanceofrain":0,"chanceofremdry":87,"chanceofwindy":0,"chanceofovercast":25,"chanceofsunshine":82,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":1},{"time":"600","temperature":46,"wind_speed":6,"wind_degree":329,"wind_dir":"NNW","weather_code":116,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0004_black_low_cloud.png"],"weather_descriptions":["Partly cloudy"],"precip":0,"humidity":50,"visibility":6,"pressure":1012,"cloudcover":1,"heatindex":46,"dewpoint":28,"windchill":43,"windgust":7,"feelslike":43,"chanceofrain":0,"chanceofremdry":89,"chanceofwindy":0,"chanceofovercast":11,"chanceofsunshine":86,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":1},{"time":"900","temperature":48,"wind_speed":5,"wind_degree":340,"wind_dir":"NNW","weather_code":113,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png"],"weather_descriptions":["Sunny"],"precip":0,"humidity":45,"visibility":6,"pressure":1015,"cloudcover":2,"heatindex":48,"dewpoint":27,"windchill":46,"windgust":6,"feelslike":46,"chanceofrain":0,"chanceofremdry":87,"chanceofwindy":0,"chanceofovercast":23,"chanceofsunshine":86,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":3},{"time":"1200","temperature":55,"wind_speed":4,"wind_degree":294,"wind_dir":"WNW","weather_code":116,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0002_sunny_intervals.png"],"weather_descriptions":["Partly cloudy"],"precip":0,"humidity":33,"visibility":6,"pressure":1016,"cloudcover":1,"heatindex":55,"dewpoint":27,"windchill":55,"windgust":5,"feelslike":55,"chanceofrain":0,"chanceofremdry":91,"chanceofwindy":0,"chanceofovercast":12,"chanceofsunshine":87,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":4},{"time":"1500","temperature":57,"wind_speed":5,"wind_degree":221,"wind_dir":"SW","weather_code":116,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0002_sunny_intervals.png"],"weather_descriptions":["Partly cloudy"],"precip":0,"humidity":31,"visibility":6,"pressure":1016,"cloudcover":3,"heatindex":57,"dewpoint":28,"windchill":57,"windgust":6,"feelslike":57,"chanceofrain":0,"chanceofremdry":86,"chanceofwindy":0,"chanceofovercast":35,"chanceofsunshine":78,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":4},{"time":"1800","temperature":54,"wind_speed":6,"wind_degree":204,"wind_dir":"SSW","weather_code":116,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0004_black_low_cloud.png"],"weather_descriptions":["Partly cloudy"],"precip":0,"humidity":36,"visibility":6,"pressure":1017,"cloudcover":12,"heatindex":54,"dewpoint":28,"windchill":54,"windgust":6,"feelslike":54,"chanceofrain":0,"chanceofremdry":86,"chanceofwindy":0,"chanceofovercast":38,"chanceofsunshine":85,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":1},{"time":"2100","temperature":52,"wind_speed":4,"wind_degree":159,"wind_dir":"SSE","weather_code":116,"weather_icons":["https:\/\/assets.weatherstack.com\/images\/wsymbols01_png_64\/wsymbol_0004_black_low_cloud.png"],"weather_descriptions":["Partly cloudy"],"precip":0,"humidity":40,"visibility":6,"pressure":1019,"cloudcover":36,"heatindex":52,"dewpoint":28,"windchill":50,"windgust":5,"feelslike":50,"chanceofrain":0,"chanceofremdry":87,"chanceofwindy":0,"chanceofovercast":40,"chanceofsunshine":80,"chanceoffrost":0,"chanceofhightemp":0,"chanceoffog":0,"chanceofsnow":0,"chanceofthunder":0,"uv_index":1}]}}} function getPropByIndex(obj, index) { for (let [i,k] of Object.keys(obj).entries()) { if (i === index) { return obj[k]; } } } // {{ (getPropByIndex(obj.forecast, 0)).hourly[0].weather_code }} // or w/o a fn // {{ Object.entries(obj.forecast)[0][1].hourly[0].weather_code }}
d3 variable equals the string "function(d)", not the value the function returns
In some d3js code, I am using an anonymous function(d) to return the value of -importance from a JSON file. I use the returned value, stored in kwdAssbly object, to decide whether or not to render part of a diagram. where I break on: kwdAssbly.opt = (function(d){ return d["-importance"]; }); With a watch set on the object kwdAssbly, the debugger shows numerical values for kwdAssbly.width & kwdAssbly.height but shows kwdAssbly.opt = kwdAssbly.opt(d). I'm expecting a string value of either required or optional! If I put a watch on d in the function, it shows -importance:"optional", but this isn't assigned to my kwdAssbly.opt object attribute Why is the function declaration being returned as the value? Here's a code snippet of the context: .attr("nullAttrib", function(d, i) { // calculate the text width and store it var kwdAssbly = {}; //the keyword group's height and width object kwdAssbly.width = this.getBoundingClientRect().width + padding; kwdAssbly.height = this.getBoundingClientRect().height; kwdAssbly.opt = (function(d){ return d["-importance"]; }); kwdProps[i] = kwdAssbly; if (i>0){ kwdX += kwdProps[i-1].width; if (kwdProps[i].opt == "optional"){ OptOffset = 40; var Lsiding = kwdgrp.append(function(){return sidingL}) .attr("transform","translate(" + kwdX + ", " + (kwdProps[i].height*2/3 + line1y + OptOffset) + ")"); var Rsiding = kwdgrp.append(function(){return sidingR}) .attr("transform","translate(" + kwdX+50 + ", " + (kwdProps[i].height*2/3 + line1y + OptOffset) + ")"); } else { OptOffset = 0; } }
Working/correct answer by Altocumulus: You won't need an anonymous function to get the string value. Just use kwdAssbly.opt = d["-importance"];
Use HTML5 (datalist) autocomplete with 'contains' approach, not just 'starts with'
(I can't find it, but then again I don't really know how to search for it.) I want to use <input list=xxx> and <datalist id=xxx> to get autocompletion, BUT I want the browser to match all options by 'contains' approach, instead of 'starts with', which seems to be standard. Is there a way? If not simply, is there a way to force-show suggestions that I want to show, not those that the browser matched? Let's say I'm typing "foo" and I want to show options "bar" and "baz". Can I force those upon the user? If I just fill the datalist with those (with JS), the browser will still do its 'starts with' check, and filter them out. I want ultimate control over HOW the datalist options show. NOT over its UI, flexibility, accessibility etc, so I don't want to completely remake it. Don't even suggest a jQuery plugin. If I can ultimate-control form element validation, why not autocompletion, right? edit: I see now that Firefox does use the 'contains' approach... That's not even a standard?? Any way to force this? Could I change Firefox's way? edit: I made this to illustrate what I'd like: http://jsfiddle.net/rudiedirkx/r3jbfpxw/ HTMLWG's specs on [list] W3's specs on datalist DavidWalsh example HONGKIAT's summary on behaviors..?
'contains' approach Maybe this is what you are looking for (part 1 of your question). It goes with the limitation of "starts with" and changes when a selection is made. 'use strict'; function updateList(that) { if (!that) { return; } var lastValue = that.lastValue, value = that.value, array = [], pos = value.indexOf('|'), start = that.selectionStart, end = that.selectionEnd, options; if (that.options) { options = that.options; } else { options = Object.keys(that.list.options).map(function (option) { return that.list.options[option].value; }); that.options = options; } if (lastValue !== value) { that.list.innerHTML = options.filter(function (a) { return ~a.toLowerCase().indexOf(value.toLowerCase()); }).map(function (a) { return '<option value="' + value + '|' + a + '">' + a + '</option>'; }).join(); updateInput(that); that.lastValue = value; } } function updateInput(that) { if (!that) { return; } var value = that.value, pos = value.indexOf('|'), start = that.selectionStart, end = that.selectionEnd; if (~pos) { value = value.slice(pos + 1); } that.value = value; that.setSelectionRange(start, end); } document.getElementsByTagName('input').browser.addEventListener('keyup', function (e) { updateList(this); }); document.getElementsByTagName('input').browser.addEventListener('input', function (e) { updateInput(this); }); <input list="browsers" name="browser" id="browser" onkeyup="updateList();" oninput="updateInput();"> <datalist id="browsers"> <option value="Internet Explorer"> <option value="Firefox"> <option value="Chrome"> <option value="Opera"> <option value="Safari"> </datalist> Edit A different approach of displaying the search content, to make clear, what happens. This works in Chrome as well. Inspired by Show datalist labels but submit the actual value 'use strict'; var datalist = { r: ['ralph', 'ronny', 'rudie'], ru: ['rudie', 'rutte', 'rudiedirkx'], rud: ['rudie', 'rudiedirkx'], rudi: ['rudie'], rudo: ['rudolf'], foo: [ { value: 42, text: 'The answer' }, { value: 1337, text: 'Elite' }, { value: 69, text: 'Dirty' }, { value: 3.14, text: 'Pi' } ] }, SEPARATOR = ' > '; function updateList(that) { var lastValue = that.lastValue, value = that.value, array, key, pos = value.indexOf('|'), start = that.selectionStart, end = that.selectionEnd; if (lastValue !== value) { if (value !== '') { if (value in datalist) { key = value; } else { Object.keys(datalist).some(function (a) { return ~a.toLowerCase().indexOf(value.toLowerCase()) && (key = a); }); } } that.list.innerHTML = key ? datalist[key].map(function (a) { return '<option data-value="' + (a.value || a) + '">' + value + (value === key ? '' : SEPARATOR + key) + SEPARATOR + (a.text || a) + '</option>'; }).join() : ''; updateInput(that); that.lastValue = value; } } function updateInput(that) { var value = that.value, pos = value.lastIndexOf(SEPARATOR), start = that.selectionStart, end = that.selectionEnd; if (~pos) { value = value.slice(pos + SEPARATOR.length); } Object.keys(that.list.options).some(function (option) { var o = that.list.options[option], p = o.text.lastIndexOf(SEPARATOR); if (o.text.slice(p + SEPARATOR.length) === value) { value = o.getAttribute('data-value'); return true; } }); that.value = value; that.setSelectionRange(start, end); } document.getElementsByTagName('input').xx.addEventListener('keyup', function (e) { updateList(this); }); document.getElementsByTagName('input').xx.addEventListener('input', function (e) { updateInput(this); }); <input list="xxx" name="xx" id="xx"> <datalist id="xxx" type="text"></datalist>
yet this thread is posted about 2 years ago. but if you are reading this thread, you maybe need to check a newer version of your browser: Current specification: https://html.spec.whatwg.org/multipage/forms.html#the-list-attribute User agents are encouraged to filter the suggestions represented by the suggestions source element when the number of suggestions is large, including only the most relevant ones (e.g. based on the user's input so far). No precise threshold is defined, but capping the list at four to seven values is reasonable. If filtering based on the user's input, user agents should use substring matching against both the suggestions' label and value. And when this post written, behavior of Firefox (51) and Chrome (56) had already been changed to match the specification. which means what op want should just work now.
this fiddle here has cracked what you are asking for But I am not sure how to make it work without this dependency as the UI looks bit odd and out of place when used along with Bootstrap. elem.autocomplete({ source: list.children().map(function() { return $(this).text(); }).get()
I found this question because I wanted "starts with" behavior, and now all the browsers seem to implement "contains". So I implemented this function, which on Firefox (and probably others), if called from input event handler (and optionally, from focusin event handler) provides "starts with" behavior. let wrdlimit = prefix => { let elm = mydatalist.firstElementChild; while( elm ) { if( elm.value.startsWith( prefix )) { elm.removeAttribute('disabled'); } else { elm.setAttribute('disabled', true ); } elm = elm.nextElementSibling; } }
Sorted Object/Map in AS3 Flex?
Is it possible to sort an object or have some sort of order in an object in Actionscript 3 Flex? I have an object which is created like so: private var data:Object = new Object(); I then go on to put some keys and values into it: this.data.someKeyOne = 0; this.data.someKeyTwo = 1337; this.data.someKeyThree = 123; After that I loop through the object: for (var dataPart:String in this.data) { trace("Key: " + dataPart = " Value:" + this.data["dataPart"]); } But my issue is that the data will not be displayed in the order I initialized them in. This is frustrating as it is required to be in the order initialized.
As #helloflash said in his answer about loop through an object, and according to Adobe's definition of associative array (which is an instance of the Object class) : An associative array, sometimes called a hash or map, uses keys instead of a numeric index to organize stored values. Each key in an associative array is a unique string that is used to access a stored value. An associative array is an instance of the Object class, which means that each key corresponds to a property name. Associative arrays are unordered collections of key and value pairs. Your code should not expect the keys of an associative array to be in a specific order. The behavior that you got is normal and you can not get ordered keys in your case (using an Object like that). If you don't need keys, you can do as #helloflash said in his answer, using a simple Array or Vector. Otherwise you can use an Array of objects, like this : var obj:Object, i:int, s:String; var data_array:Array = [ {key: 'someKeyOne', value: 0}, {key: 'someKeyTwo', value: 1337}, {key: 'someKeyThree', value: 123} ] for(i = 0; i < data_array.length; i++){ obj = data_array[i]; trace('Key : ' + obj.key + ', Value = ' + obj.value); } for (s in data_array) { obj = data_array[s]; trace('Key : ' + obj.key + ', Value = ' + obj.value); } for each (obj in data_array){ trace('Key : ' + obj.key + ', Value = ' + obj.value); } // all these 3 loops give : // Key : someKeyOne, Value = 0 // Key : someKeyTwo, Value = 1337 // Key : someKeyThree, Value = 123 Or you can use Object and then sort it into an Array like this : var data_object:Object = new Object(); data_object.someKeyOne = {index:0, value: 0}; data_object.someKeyTwo = {index:1, value: 1337}; data_object.someKeyThree = {index:2, value: 123}; var tmp_array:Array = sort_obj(data_object); for(i = 0; i < tmp_array.length; i++){ obj = tmp_array[i]; trace('Key : ' + obj.key + ', Value = ' + obj.value); } for (obj in tmp_array) { obj = tmp_array[obj]; trace('Key : ' + obj.key + ', Value = ' + obj.value); } for each (obj in tmp_array){ trace('Key : ' + obj.key + ', Value = ' + obj.value); } function sort_obj(obj:Object):Array { var a:Array = []; for (var key:String in obj) { a.push({key: key, index: obj[key].index, value: obj[key].value}); } a.sortOn('index', Array.NUMERIC); return a; } // all these 3 loops give : // Key : someKeyOne, Value = 0 // Key : someKeyTwo, Value = 1337 // Key : someKeyThree, Value = 123 Hope all that can help you.
Adobe help about looping: The for..in loop iterates through the properties of an object, or the elements of an array. For example, you can use a for..in loop to iterate through the properties of a generic object (object properties are not kept in any particular order, so properties may appear in a seemingly random order) Conclusion If you want your keys to appear in order, you must use an Array (or a Vector): var myArray:Array = [0, 1337, 123]; for (var i:String in myArray) { trace(myArray[i]); } // output: 0, 1337, 123
CRM 2011: Getting entity with Javascript
I am working on some CRM 2011 Online customisations and I need to get an entity using javascript. The entity I need will be based on the ID value of another field (a Contact entity) - this Contact ID I can get fine. The entity I want is a custom entity. There may be multiple matches based on the Contact ID so I just want to get the first one in the list (order not important) So far I have looked into a few ways to do this... OData - I couldn't find enough examples on this as to what query expressions I can create, also I don't know if/how to make this work for custom entities FetchXML - I can create a nice FetchXML query using the built-in "advanced find" too and would be happy to call this from javascript if anyone can help? I found one promising answer here but I could not see how the "results" return data was being set (Service.Fetch function) SOAP Request - First thing I tried is a similar method as I could have done in CRM 4 but this does not seem to work. Although the request executes, my result data just seems to be empty. This is all I have code for so if any one can spot a problem with the code below then that would be great. EDIT: I have spotted some redundant query data (I had removed link opening tags but left closing tags) - since removing this I now get XML result data... however, the where clause does not seem to apply (just get list of all entities) var xml = "<?xml version='1.0' encoding='utf-8'?>" + "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" + GenerateAuthenticationHeader() + "<soap:Body>" + "<RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" + "<query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" + "<q1:EntityName>new_vehicle</q1:EntityName>" + "<q1:ColumnSet xsi:type='q1:ColumnSet'>" + "<q1:Attributes>" + "<q1:Attribute>new_vehicleid</q1:Attribute>" + "<q1:Attribute>new_primarydriver</q1:Attribute>" + "<q1:Attribute>statuscode</q1:Attribute>" + "<q1:Attribute>new_registration</q1:Attribute>" + "</q1:Attributes>" + "</q1:ColumnSet>" + "<q1:Distinct>false</q1:Distinct>" + "<q1:Conditions>" + "<q1:Condition>" + "<q1:AttributeName>new_primarydriver</q1:AttributeName>" + "<q1:Operator>Equal</q1:Operator>" + "<q1:Values>" + "<q1:Value xmlns:q2='http://microsoft.com/wsdl/types/' xsi:type='q2:guid'>" + customerID + "</q1:Value></q1:Values></q1:Condition>" + "</q1:Conditions>" + "</query></RetrieveMultiple>" + "</soap:Body></soap:Envelope>"; var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP"); xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false); xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple"); xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8"); xmlHttpRequest.setRequestHeader("Content-Length", xml.length); xmlHttpRequest.send(xml); var result = xmlHttpRequest.responseXML.xml; var doc = new ActiveXObject("MSXML2.DOMDocument"); doc.async = false; doc.loadXML(result); var id = doc.selectSingleNode("//new_vehicleid"); var registration = doc.selectSingleNode("//new_registration"); if(id == null) return null; var vehicle = new Array(); value[0] = new Object(); value[0].id = id; value[0].name = registration; value[0].entityType = "new_vehicle"; return vehicle; Sorry about the big code post but hopefully somebody who has a better understanding can help
Firstly, thanks to GlennFerrieLive for his answer post. The samples I found with the Dynamics CRM 2011 SDK (well just one in particular) really helped and the JSON parser included was perfect for the job! I am posting this answer to give a full example of how I did it with some important comments to pay attention to which may not be so obvious from the SDK examples. Get selected ID value from lookup field The aim of my task was to use javascript to get set a lookup field, based on the selected data of another lookup entity. The entity to set is "new_vehicle" and the entity to query on is "customer". First job is to get the ID value of the contact lookup field... var customerItem = Xrm.Page.getAttribute("customerid").getValue(); var customerID = customerItem[0].id; Querying an entity using an ID Next is the part where I used the customerID value to find the vehicle that is currently assigned to them (the entity I want to use to set a lookup field). First problem I found was that when querying with OData, the ID value does not seem to work with curly brackets {} - so these need to be removed... customerID = customerID.replace('{', '').replace('}', ''); Next we get the oDataPath... var oDataPath = Xrm.Page.context.getServerUrl() + "/xrmservices/2011/organizationdata.svc"; Then we can construct the OData query... var filter = "/new_vehicleSet?" + "$select=new_vehicleId,new_Registration" + "&$filter=new_PrimaryDriver/Id eq (guid'" + customerID + "')" + "&$orderby=new_LastAllocationDate desc" + "&$top=1"; NOTE: There are a couple of important things to note here... When using a guid value you must explicitly say it is a guid using (guid'xxx') When filtering by a lookup entity (e.g. new_PrimaryDriver) you must append the value to query (e.g. Id) - this results in new_PrimaryDriver/Id Once we have the query setup we can request the data as follows... var retrieveRecordsReq = new XMLHttpRequest(); retrieveRecordsReq.open("GET", oDataPath + filter, true); retrieveRecordsReq.setRequestHeader("Accept", "application/json"); retrieveRecordsReq.setRequestHeader("Content-Type", "application/json; charset=utf-8"); retrieveRecordsReq.onreadystatechange = function () { if (this.readyState == 4) { if (this.status == 200) { var retrievedRecords = JSON.parse(retrieveRecordsReq.responseText).d; if(retrievedRecords.results.length > 0) { var vehicle = retrievedRecords.results[0]; SetLookup("new_replacedvehicle", vehicle.new_vehicleId, vehicle.new_Registration, "new_vehicle"); } } } }; retrieveRecordsReq.send(); Note that this is an asynchronous call and the onreadystatechange function will be processed upon completion, in this function we do a couple of checks to see if it was a success and the we parse the resulting JSON data - the JSON.Parse function has been included at the bottom of this post (but is available from the SDK) Setting a lookup field using the entity queried above The other function to make note of here is SetLookup which is just a simple helper function I added to set a lookup field. This is as follows... function SetLookup(fieldName, idValue, textValue, typeValue) { var value = new Array(); value[0] = new Object(); value[0].id = idValue; value[0].name = textValue; value[0].typename = typeValue; Xrm.Page.getAttribute(fieldName).setValue(value); } JSON parse function This is the JSON helper function that was used in the above code (JSON.parse), pasted as it was found in the SDK... if (!this.JSON) { this.JSON = {}; } (function () { function f(n) { return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }, rep; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { var i, k, v, length, mind = gap, partial, value = holder[key]; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } if (typeof rep === 'function') { value = rep.call(holder, key, value); } switch (typeof value) { case 'string': return quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if (!value) { return 'null'; } gap += indent; partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { var i; gap = ''; indent = ''; if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } else if (typeof space === 'string') { indent = space; } rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } return str('', { '': value }); }; } if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { var j; function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '#').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({ '': j }, '') : j; } throw new SyntaxError('JSON.parse'); }; } } ());