2

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"
    },

]
1
  • 1
    try objectData[0][objectName] or objectData[0][fx] Commented Feb 15, 2022 at 9:19

1 Answer 1

1

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");
Sign up to request clarification or add additional context in comments.

3 Comments

Why does this work?
It is because before you were using console.log(objectData[0].fx); which means it was assigning the address of fx to get the node value which is wrong and it will give you an undefined value as it does not exist. but when you change that to [fx] it means first to get the value of fx and then use it to get the node. I hope my explanation helps you.
amazing. Thank you for the help Ghazni.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.