Home > Blockchain >  How do I grab specific data dynamically from an array of objects?
How do I grab specific data dynamically from an array of objects?

Time:02-16

Situation

I have code that takes a local JSON file and parses it into an object. This part works perfectly.

My goal is to create a function that takes two parameters:

  1. The path of the JSON file to be parsed.
  2. The property name of a specific object so I can grab the value behind the key.

Problem

I added a variable (objectName) to pass the property name. I also added [0].fx so I can call the data from the first object only. When I run my code, I get Undefined.

Where did I go wrong?

(in the example code below, I was aiming to get "David")

const localDataObject = (fileName, objectName) => {
const localData = path.join(__dirname, "../", fileName);

fs.readFile(localData, (err, data) => {
   const objectData = JSON.parse(data);
   const fx = objectName;
        console.log(objectData[0].fx);
    });
};

localDataObject("./Family.json", "name");

the first object looks like this:

[
    {
        "name": "David",
        "age": "24",
        "role": "Studet"
    },

]

CodePudding user response:

The solution for your code is :

const localDataObject = (fileName, objectName) => {
const localData = path.join(__dirname, "../", fileName);

fs.readFile(localData, (err, data) => {
   const objectData = JSON.parse(data);
   const fx = objectName;
        console.log(objectData[0][fx]);
    });
};

localDataObject("./Family.json", "name");
  • Related