goalie35 goalie35 - 29 days ago 13
Javascript Question

Javascript: how can I populate an array of property values dynamically?

I have an array of values, which I want to insert into a property of an object, but I'm not sure how. Here's my object. The property is called "values" (located at the very bottom), and as you can see, I'm trying to insert a dynamic list of data (called "result") into it:

var myConfig = {
globals: {
fontFamily: "Roboto"
},
type: "bar",
backgroundColor: "#f4f2f2",
plotarea: {
backgroundColor: "#fff"
},
scaleX: {
lineColor: "#7d7d7d",
tick: {
lineColor: "#7d7d7d"
},
guide: {
visible: false
},
values: [result[0]["Heading"], result[1]["Heading"], result[2]["Heading"], ...],

}};


Is there any way I can set this up to dynamically place this result["Heading"] data into my "values" property?

Thanks

Answer

So, assuming results is an array of objects that have the Heading property, you can get an array of only those, using the map function, like this:

values: result.map(function(item){ return item.Heading; })

map is a new-ish function, defined in ECMAScript 5.1, but all major browsers support it. Basically, for every item in the array, it will execute the provided selector function, and return the result. So, you're starting with an array of objects having a Heading property, and ending up with an array of the Heading property values themselves.