Search code examples
node.jsdatabaseobject

Retrieving data from objects with a variable in nodejs


How to get values from an object in nodejs?

let person = {temperature:[35,36],humidity:[85,90,89};

let y = req.query.id; (which is `temperature`)
console.log(person.y);

Solution

  • In order to get values from a nodejs object you can do it in the following way

    Getting it directly person.temparature or person[myvar]

    Or by iteration:

    for (const [key, value] of Object.entries(person)) {
      console.log(`${key}: ${value}`); // key = 'temperature', value = [35,36] for the first entry (temperature)
    }
    

    Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors