Home > Mobile >  Access nested JSON object without specifying key in JavaScript
Access nested JSON object without specifying key in JavaScript

Time:01-22

I decided to learn more on JavaScript looping and mapping functions by doing nested objects/arrays. Now I stumbled into a problem which is somewhat similar to this but far more complicated.

enter image description here

In which I needed to write another function again in order to trim and combine those characters just to get every employees position. Is there a way I can get every employees position without specifying their name? Like a one line variable declaration(not working) like this:

let position = Object.keys(employees)[0].position;

In which I can insert it inside my loop so I can delete my existing accessJson function and lessen my code.

EDIT:

Please don't mark my question as a duplicate one. I think I already mentioned it above that my code is fine and perfectly working. What I wanted to get feedback is, can we optimize my code into a one line declaration so we can get rid of accessJson function and avoid the creation of another function that will trim and combine those characters just to get every employees position.

My question and accessJson function is similar to this:

How can I access and process nested objects, arrays or JSON?

CodePudding user response:

const data = {
  "employees": {
      "Gill Bates": {
          "position": "Software Engineer",
          "office": "Tokyo, Japan"
      },
      "Jebron Lames": {
          "position": "Full-stack Developer",
          "office": "Manila, Philippines"
      }
  }
};

const { employees } = data;

const extract = (p) => Object.keys(employees).map(name => employees[name][p]);

console.log('get every employees position', extract('position'));
console.log('get every employees office', extract('office'));

  •  Tags:  
  • Related