0

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.

Accessing elements of JSON object without knowing the key names

here's my JSON:

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

and my accessJson function which is the famous solution for nested JSON objects:

function accessJson(obj) {
  const result = [];
  for (const prop in obj) {
    const value = obj[prop];
    if (typeof value === 'object') {
      result.push(toArray(value));
    } else {
      result.push(value);
    }
  }
  return result;
}

The code is working perfectly fine in accessing the JSON object. But the problem is that I'm getting a return which looks like this:

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?

Ivan Gray
  • 55
  • 6

1 Answers1

1

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'));
Ian
  • 1,198
  • 1
  • 5
  • 15