skip to Main Content

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


  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].

    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search