获取嵌套对象中的特定值并保存到变量中



我在data.json文件中有一个具有不同id的对象。我想通过type === admin获取一个特定的id,并将其保存到一个名为adminID的变量中。我怎样才能做到这一点呢?

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);
}
};

您可以使用.filter()获得具有.type === 'admin'的用户数组,然后使用.map()将用户对象转换为ID字符串。就像这样(代码片段包含JSON,您可能需要向下滚动一点):

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);

如果只有一个管理员,那么您可以使用adminIDs[0]获取ID。

您可以按键筛选学生数组,这里演示硬编码输入:

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);
})();

输出:

admins: 6779300283

最新更新