1

i have an object in a data.json file with different ids. I want to grab a specific id by if the type === admin and save it to a variable called adminID. How can I achieve this?

data.json

{
    "name": "data record",
    "students": [
        {
            "id": "b4cbbdd1",
            "type": "register",
            "access": {
                "accesskey": "6783902",
                "accesscode": "0902j"
            }
        },
        {
            "id": "u83002839940",
            "type": "student"
        },
        {
            "id": "7939020",
            "type": "teacher",
            "subject": []
        },
        {
            "id": "6779300283",
            "type": "admin",
            "status": "full-time"
        },
        {
            "id": "79300e8",
            "type": "worker",
            "schedule": [
                {
                    "morning": "zone A"
                }
            ],
            "repeat": "yes"
        }
    ]
}

index.js

async function dataReader(filePath, data) {
  const result = await fs.readFile(filePath);
  try {
    return JSON.parse(result);
  } catch (err) {
    console.error(err);
  }
}

const saveId = async () => {
    try {
      const readData = await dataReader("./data.json");

      //grab id from data.json and save to a variable
  
    } catch (err) {
      console.error(err);
    }
  };

2 Answers 2

1

You can just use .filter() to get an array of the users with .type === 'admin', then use .map() to convert the user objects into ID strings. Just like this (snippet includes the JSON, you might need to scroll down a bit):

const data = JSON.parse(`{
    "name": "data record",
    "students": [
        {
            "id": "b4cbbdd1",
            "type": "register",
            "access": {
                "accesskey": "6783902",
                "accesscode": "0902j"
            }
        },
        {
            "id": "u83002839940",
            "type": "student"
        },
        {
            "id": "7939020",
            "type": "teacher",
            "subject": []
        },
        {
            "id": "6779300283",
            "type": "admin",
            "status": "full-time"
        },
        {
            "id": "79300e8",
            "type": "worker",
            "schedule": [
                {
                    "morning": "zone A"
                }
            ],
            "repeat": "yes"
        }
    ]
}`);

adminIDs = data.students.filter(user => user.type === 'admin').map(user => parseInt(user.id));

console.log(adminIDs);

If there's only one admin, then you can get the ID with adminIDs[0].

Sign up to request clarification or add additional context in comments.

Comments

0

You can filter the students array by key, here demoing with hard-coded input:

const input = `{ "name": "data record", "students": [ { "id": "b4cbbdd1", "type": "register", "access": { "accesskey": "6783902", "accesscode": "0902j" } }, { "id": "u83002839940", "type": "student" }, { "id": "7939020", "type": "teacher", "subject": [] }, { "id": "6779300283", "type": "admin", "status": "full-time" }, { "id": "79300e8", "type": "worker", "schedule": [ { "morning": "zone A" } ], "repeat": "yes" } ] }`

async function dataReader(filePath, data) {
  //const result = await fs.readFile(filePath);
  const result = input;
  try {
    return JSON.parse(result);
  } catch (err) {
    console.error(err);
  }
}

const extractByKeyValue = async (key, value, extract) => {
  try {
      const readData = await dataReader("./data.json");
      if(Array.isArray(readData.students)) {
        return readData.students.filter(obj => {
          return obj[key] === value;
        }).map(obj => obj[extract]).join(', ');
      } else {
        return 'ERROR: JSON does not have a students array';
      }
  } catch (err) {
    console.error(err);
    return 'ERROR: JSON parse error, ' + err;
  }
};

(async() => {
  let admins = await extractByKeyValue('type', 'admin', 'id');
  console.log('admins:', admins);
})();

Output:

admins: 6779300283

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.