Reputation: 3159
I have an array of objects and I want to add a prop of type Object
to every object, just that the value of the field will be dynamic.
var data= [
{ name:"Jan", y:0 },
{ name:"Feb", y: 71.5 },
{ name: "Mar", y:106.4 },
{ name: "Apr", y:106.4 },
{ name: "May", y:0 },
{ name: "Jun", y:106.4 },
{ name: "Jul", y:166.4 },
{ name: "Aug", y:36.4 },
{ name: "Sep", y:0 },
{ name: "Oct", y:26.4 },
{ name: "Nov", y:206.4 },
{ name: "Dec", y:92.4 }
]
now I want to add a prop to it. //added prop to the first item in the array.
data[0].plot = {rad: 1}
My issue is:
1) how can I add the "plot"
object to every single item in the data
2) the value of rad
should be such a way that it should correspond to the value of 'y' in the data
i.e: if value of 'y' =0,
(its min value in the data) then the "rad" value should be 1,
similarly: value of y=206.4
(its max value), then rad
should be 10.
The "rad" values in between 0 and 206.4 should correspond to the values of 'y' and fall between 1-10 (this is the "rad" range).
I hope this makes sense. I'll clarify with details if needed, Thanks in advance!!
Upvotes: 0
Views: 45
Reputation: 19772
You can do something like this (check out the jsbin):
data.forEach(datum => {
datum.plot = {
rad: (10 * datum.y)/206.4 || 1
}
})
I think that's the right formula for converting your y
to rad
... Anyway, the principle is that you can just loop through objects and attach the property to each one dynamically. Aside from the programming aspect, you'll just need to figure out whatever the correct math formula is, and then put it in there to calculate whatever value you need.
Upvotes: 3