I have a file called contentful.json which is stored in the root of my directory.
This is what that file looks like:
[{
"URL": "/force",
"SpaceID": "2g1335I9GYQCKwmQYCuSSI"
}, {
"URL": "/heroku",
"SpaceID": "2g1335I9GYQCKwmQYCuSSI"
}, {
"URL": "/slack",
"SpaceID": "2g1335I9GYQCKwmQYCuSSI"
}, {
"URL": "/contentful",
"SpaceID": "2g1335I9GYQCKwmQYCuSSI"
}, {
"URL": "/openShift",
"SpaceID": "2g1335I9GYQCKwmQYCuSSI"
}]
I then have a file called contentful.js.
Which looks like this:
const fs = require('fs');
let obj;
fs.readFile('./contentful.json', 'utf8', (err, jsonData) => {
if (err) throw err;
obj = JSON.parse(jsonData);
// Method One
for (let i = 0, l = obj.length; i < l; i++) {
console.log(obj.URL);
// ...
}
// Method Two
Object.keys(obj).forEach((key) => {
if (key.url === '/heroku') {
console.log(key.SpaceID);
}
});
});
What I am trying to do is read the contentful.json file from the contentful.js file. Which works.
Then I am trying to loop through that file and find a specific value.
E.G loop through the JSON object, and where URL equals a dynamic value (/force) return me the SpaceID.
So this JSON object could be n big. I have attempted two solutions but don't think I am quite their yet.
I need to input a URL into the contnetful.js file and if that URL matches the URL in the contnetful.json file I would like it to return that SpaceID.
console.log(obj.URL)isundefined. It printsundefinedout as many time as the size of the JSON object. In this case 5. However for Method Twoconsole.log(key.SpaceID);it doesn't print anything out.