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

tzcvj98z  于 2022-12-21  发布在  Java
关注(0)|答案(2)|浏览(138)

我在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);
    }
  };
nfs0ujit

nfs0ujit1#

你可以使用.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。

ccrfmcuu

ccrfmcuu2#

您可以按键过滤students数组,下面使用硬编码输入进行演示:

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

相关问题