Change A Property For Every Dynamic Object In A Variable - javascript

I am storing JSON objects with a name and token value
Example Object in tokenHandler.json
{
"A Random Name":{
"token": 0
}
}
My Goal Is to have a function add + 1 to token for every object in the JSON File every 5 seconds
function addToken() {
const fs = require("fs");
const tokenHander = require("tokenHandler.json");
// My question is on this line of code
tokenHandler.token = tokenHandler.token + 1;
fs.writeFile("tokenHandler.json", JSON.stringify(tokenHandler), (error) => {
if (error) return console.log(error);
});
return console.log("Added Token!");
}
setInterval(addToken, 5000);
What im having trouble with is accessing every object inside tokenHandler. With the current line; a 2nd "token" property is added into the object instead of incrementing the original. I want to have a way to access and change every token property of every object present in the json file regardless of the name of the object

You can use the Object.values method to accomplish this. Object.values() will return an array of the values of object, which can then be chained using forEach to increase the value of token
function addToken() {
const fs = require('fs')
const tokenHander = require('tokenHandler.json')
Object.values(tokenHander).forEach(item => item.token++)
fs.writeFile('tokenHandler.json', JSON.stringify(tokenHandler), (error) => {
if (error) return console.log(error)
})
return console.log('Added Token!')
}
setInterval(addToken, 5000)

Related

Filter Array of objects (API response) based on flag in database

I am receiving a large array of objects using the below method:
const GetList = async () => {
const [data, error] = await GetList();
console.log(response);
This gives me back an array of 1000 elements, there is an isActive flag on every element and I need to filter out the elements that are not active.
I am not able to use
var resultFiltered = response.filter(obj =>{
return obj.isActive === 'true'
});
As it gives me an error message
The entire array is stored in the data variable, how can I filter out all elements that are not active?
I'm not sure why you are using response variable, since the value is fetched variable data, try filtering as shown below
const GetList = async () => {
const data = await GetList();
const resultFiltered = data.filter(obj => Boolean(obj.isActive) === true);
console.log(resultFiltered);
}
According to the error, the response variable is not an array-type variable please check that out. If it's an object then convert it into an array and then apply the filter function.
const resultFiltered = Object.values(response).filter(obj => obj.isActive === true);
Test the bellow code:
response.data.filter()

How to synchronise my code execution in angular

I'm performing multiple task and each task is dependent on previous task execution. So in my example what I want is after getting all the Id, i should get their respective blob value and then finish the execution by storing it in a variable. I'm very new to javascript and angular, please help me out. Here's what I'm trying
//this method will get the response from the rest api
async getIDFromAssets(){
this.blobDataArray=[];
this.service.getAssetsData().subscribe(async (res: JSON) => {
//after getting the response I'm filtering through it to get sepcific Id using this.getFileId() method
this.getFileId(res).then((data)=>{
console.log("blob "+data)
})
})
}
//below method will get one Id at a time and will call another method to get it's blob value
async getFileId(res){
this.fileId = [];
Object.keys(res).forEach(keys => {
if (keys == 'emb') {
let responseValue = res[keys];
Object.keys(responseValue).forEach(async (keys1) => {
if (keys1 === 'file') {
let responseArray = responseValue[keys1];
for (let file of responseArray) {
let temp: string = file.metadata.contentType;
if (temp.startsWith('image')) {
//Here I'm getting id value 'file._id' and using that I'm calling another method 'getBlobData()' to get its blob value
let data=await this.getBlobData(file._id);
this.blobDataArray.push(data);
}
}
return this.blobDataArray
}
});
}
});
}
// method to get the blob value
async getBlobData(fileId){
this.articleDetailService.getBlobDataFromAssets(fileId).subscribe(async (res)=>{
let imageObj={
'id':fileId,
'blob':res
}
return imageObj;
})
}
You need to use RxJs to avoid the nested subscription to chain your calls, possible methods to use are mergeMap and filter
Please take a look at this answer here.

How do I destructure this deep nested object?

I have this function below:
const displayUserPhotoAndName = (data) => {
if(!data) return;
// add your code here
clearNotice();
};
the data parameter is an API from https://randomuser.me/api/
The assignment has the instructions below:
Locate the displayUserPhotoAndName function and do the follwing within it:
After the first if(!data) return; statement that terminates the
function if the expected data parameter is not provided, create a
statement that de-structures the data parameter and obtains the
results property from it;
Create a second statement in the next line that de-structures the
results variable you just created, and obtain the first item from it
(it is an Array! See https://randomuser.me/api/). Your de-structured
array item should be declared as profile. This represents the profile
data for the user gotten from the API call that you want to display
in your app.
Step 3
Still within the displayUserPhotoAndName function :
Set the HEADING element in your app to display the title, last name,
and first name (in that order, separated by a single space) of the
user profile returned by the API.
Set the IMG in your app to display the large photo of the user
profile returned by the API.
what I have done:
const displayUserPhotoAndName = (data) => {
if(!data) return;
// add your code here
const {results} = data.results;
const [profile] = results;
const {title, First, Last} = results;
const [,,,,,,,,,picture] = results;
const largeImage = picture.large;
userImage.src = largeImage;
headerUserInfo.innerText = title + ' ' + First + ' ' + Last;
clearNotice();
displayExtraUserInfo(profile);
};
The error I get:
You have not de-structured the 'results' property from the 'data'
parameter passed to 'displayUserPhotoAndName' function
I'm in dire need of assistance. Thanks in anticipation
I'm not going to provide you the full answer but giving you the hints:
const { results } = data
const { profile } = results
console.log(profile)
Can be written as:
const { results: { profile } } = data
console.log(profile)
Here are my some posts from which you may go further:
destructure an objects properties
how is this type annotation working
why source target when destructuring

Querying MySQL with JS Object returning [object Object] as table name

I'm building a program that queries MySQL databases, gets the tables, fields, field data types, and entries and returns it as a single object to be later used to view the MySQL data as a table.
This is what the built object will look like:
{
`Table_Name`: {
Title: `Table_Name`,
Fields: {
`Field Name`: `Datatype`
},
RowData: []
}
}
The query to get the tables is fine, however the query to get the row data isn't. The query function looks like this:
function getRows(){
let secondpromises = [];
secondpromises.push(
new Promise((resolve, reject) => {
for(x in Tables){
Connect_SQL(SQLcreds, w_newSconn, (conn) => {
conn.query(`SELECT * FROM ${Tables[x]}`, (err, results) => {
if(err){
console.log(err);
reject(err);
}else{
for(r in results){
Tables[`${Tables[x].Title}`].RowData.push(results[r]);
}
resolve(results);
}
});
});
if(x == Tables.length - 1){
Promise.all(secondpromises).then(() => {
if(w_newSconn){
w_newSconn.close();
w_newSconn = null;
}
console.log(Tables);
});
}
}
})
);
}
The error is coming from conn.query(). It is throwing an error stating there is an error in my SQL syntax at:
SELECT * FROM [object Object]
I understand the reason why and I'm sure there is a way to resolve this through JSON.Stringify() but there must be a simpler way. I have already tried creating a variable like so:
let objArray = Object.keys(Tables)
But it still returned [object Object], any help would be appreciated.
Tables[x] is an object. You need to get the table name from it.
conn.query(`SELECT * FROM ${Tables[x].Title}`, (err, results) => {
It also looks like the property name is the same as the title, so you can do:
conn.query(`SELECT * FROM ${x}`, (err, results) => {
I ended up creating a variable in the loop
let table = keys[x]
and that did the trick, for whatever reason ${keys[x]} was returning undefined but the variable returned the table name. Theoretically I could have changed the for loops to a
for(x in Tables)
and x would have returned the title so I may go back and rewrite it that way. Thank you.

Cannot access a key value pair of a changed object

Please excuse my code
From an external source , I am given the following external data which I name loxAP3
to which I am trying to firstly retrieve svg data related to the rooms.image property and then change the incoming svg data to work with react, using the following code.
createRoomData(loxAPP3, socket) {
console.log(loxAPP3)
let rooms = []
let rawRooms = loxAPP3.rooms
for (const rawRoom in rawRooms) {
rooms.push(rawRooms[rawRoom])
}
//add svg property with blank property value
rooms.forEach((room) => {
room.svg = ''
})
//fetch image data for each room in loxApp3.rooms
rooms.forEach((room) => {
const image = room.image
socket
.send(image)
.then(function(respons) {
//console.log("Successfully fetched svg image " + respons ); // success
room.svg = respons
//console.log(room.svg) // success console returns room.svg data
},
function(err) {
console.error(err);
}
);
})
this.setState({
rooms: rooms
}, () => {
console.log(rooms) // success rooms[0].svg is shown as having been populated
this.adjustSvGImageToReact()
})
}
console.log(rooms) // success rooms[0].svg is shown as having been populated
However the problem comes when I try and manipulate the room object, if I log a property that already existed from the original data, there is no problem, however if I try an fetch the .svg property it comes back not as undefined but as the empty string I first set it to be.
adjustSvGImageToReact() {
this.state.rooms.forEach((room)=>{
console.log(room.name) // success
console.log(room.uuid) // success
console.log(room.svg) //empty
})
}
Create an array of the socket.send() promises instead of calling them inside forEach
Then you can use Promise.all() to set the state and call adjustSvGImageToReact() after the socket requests have completed
const svgPromises = rooms.map((room) => {
const image = room.image
return socket
.send(image)
.then((respons)=> room.svg = respons)
})
Promise.all(svgPromises).then(() => {
this.setState({rooms: rooms}, () => {
console.log(rooms) // success rooms[0].svg is shown as having been populated
this.adjustSvGImageToReact()
});
}).catch(err=>console.log('One of the socket requests failed'))

Categories