'Find a value in an javascript object where the amount of values varies
just scratching my head with this one. How can I extract the time remaining in seconds from the object below? Please note, the number of options varies depending on the program being run, so I somehow need to search for the "value:" associated with the "key:" "BSH.Common.Option.RemainingProgramTime".
{
"data": {
"key": "Dishcare.Dishwasher.Program.Intensiv70",
"options": [
{
"key": "BSH.Common.Option.StartInRelative",
"value": 0,
"unit": "seconds"
},
{
"key": "Dishcare.Dishwasher.Option.HalfLoad",
"value": false
},
{
"key": "Dishcare.Dishwasher.Option.IntensivZone",
"value": true
},
{
"key": "Dishcare.Dishwasher.Option.VarioSpeedPlus",
"value": false
},
{
"key": "Dishcare.Dishwasher.Option.SilenceOnDemand",
"value": false
},
{
"key": "BSH.Common.Option.ProgramProgress",
"value": 82,
"unit": "%"
},
{
"key": "BSH.Common.Option.RemainingProgramTime",
"value": 1680,
"unit": "seconds"
},
{
"key": "BSH.Common.Option.RemainingProgramTimeIsEstimated",
"value": true
},
{
"key": "BSH.Common.Option.EnergyForecast",
"value": 89,
"unit": "%"
},
{
"key": "BSH.Common.Option.WaterForecast",
"value": 70,
"unit": "%"
}
]
}
}
Solution 1:[1]
You can simply use array.find() to get the object you need.
const remainingTimeOption = myObject.data.options.find(option => option.key === "BSH.Common.Option.RemainingProgramTime");
console.log(remainingTimeOption.value);
console.log(remainingTimeOption.unit);
Solution 2:[2]
Try this
myArray.data.options.find(x => x.key == 'BSH.Common.Option.RemainingProgramTime')[0].value;
Solution 3:[3]
Thanks for the responses. I need to get more sleep, this was a stupid question with obvious answers, sorry.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | FrostyZombi3 |
| Solution 2 | Mike Irving |
| Solution 3 | Wes Thompson |
