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
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):If there’s only one admin, then you can get the ID with
adminIDs[0]
.You can filter the students array by key, here demoing with hard-coded input:
Output: