Home > Net >  Getting data with a similar key name in JavaScript
Getting data with a similar key name in JavaScript

Time:04-10

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.

CodePudding user response:

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);

CodePudding user response:

  • Using Object#entries, get the key-value pairs of channel
  • Using Array#reduce, iterate over the latter while updating the resulting object
  • In each iteration, use String#match to 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);

  • Related