'Getting data with a similar key name in JavaScript
I have this data.
{"channel":
{
"id":*******,"name":"INA229 Measurement",
"description":"Test with INA229",
"latitude":"0.0",
"longitude":"0.0",
"field1":"Voltage",
"field2":"Current",
"field3":"Power",
"field4":"Temperature",
"created_at":"2022-04-07T08:40:24Z",
"updated_at":"2022-04-07T08:40:52Z",
"last_entry_id":3771},
"feeds":[]
}
How to take only values for field(x) keys to new data. The key of the name field(x) (field1, field2, field3 ..... field8) is dynamic and varies in the range from field1 to field8 keys. I don't know how many there will be in total, even when receiving data.
Solution 1:[1]
Iterate over data.channel with for/in, check to see if the key starts with the keyword and, if it does, add the value of that property to a new object using that key.
const data = { "channel": { "id": "", "name": "INA229 Measurement", "description": "Test with INA229", "latitude": "0.0", "longitude": "0.0", "field1": "Voltage", "field2": "Current", "field3": "Power", "field4": "Temperature", "created_at": "2022-04-07T08:40:24Z", "fieldTest": "Test", "updated_at": "2022-04-07T08:40:52Z", "last_entry_id": 3771 }, "feeds": [] };
const out = {};
for (const key in data.channel) {
if (key.startsWith('field')) {
out[key] = data.channel[key];
}
}
console.log(out);
Solution 2:[2]
- Using
Object#entries, get the key-value pairs ofchannel - Using
Array#reduce, iterate over the latter while updating the resulting object - In each iteration, use
String#matchto check for the key format
const data = { "channel": { "id": "", "name": "INA229 Measurement", "description": "Test with INA229", "latitude": "0.0", "longitude": "0.0", "field1": "Voltage", "field2": "Current", "field3": "Power", "field4": "Temperature", "created_at": "2022-04-07T08:40:24Z", "updated_at": "2022-04-07T08:40:52Z", "last_entry_id": 3771 }, "feeds": [] };
const res = Object.entries(data.channel).reduce((acc, [key, value]) => {
if(key.match(/^field[1-8]$/)) {
acc[key] = value;
}
return acc;
}, {});
console.log(res);
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 | |
| Solution 2 | Majed Badawi |
