NodeJs console.table in a forloop - javascript

so there is this NodeJS module called console.table where you can basically add tables inside the console. Here is an example from their website:
// call once somewhere in the beginning of the app
require('console.table');
console.table([
{
name: 'foo',
age: 10
}, {
name: 'bar',
age: 20
}
]);
// prints
name age
---- ---
foo 10
bar 20
This is a mere example, I tried to automate it by putting it in a forloop, the forloop and code that I had hoped would work is this:
var values = [
]
for(var l = 0;l<config.accounts.username.length;l++) {
values.push([
{
username: "Number "+l,
itemtype: "Hello",
amount: 10
}, {
itemtype: "Hello",
amount: 10
}
]);
}
console.table("", values);
Unfortunatly though, it does not work, can someone help me with this?
Thanks!

You're pushing an array of values into your array - remove the [ & ]
for(var l = 0;l<config.accounts.username.length;l++) {
values.push(
{
username: "Number "+l,
itemtype: "Hello",
amount: 10
}, {
itemtype: "Hello",
amount: 10
}
);
}
Ref: Array.prototype.push
And then your original example didnt take 2 parameters it only took one so this
console.table("", values);
should possibly be
console.table(values);

Related

Calling function with a passed in array

I'm trying to write a function that will be called with an array that has information on a person such as their name and then age. I need this function to grab all of the numbers only and then return them then added up. I've done some research and it seems filter and reduce are what I need to do this in the easiest way for a total beginner like me to do?
Apologies for any typos/wrong jargon as my dyslexia gets the better of me sometimes.
An example of what kind of array is being passed into the function when called;
{ name: 'Clarie', age: 22 },
{ name: 'Bobby', age: 30 },
{ name: 'Antonio', age: 40 },
Would return the total added numbers.
// returns 92
Why isn't the array I'm calling this function with working? Can you provide me a working example without the array being hardcoded like the other answers? - I'm passing in an array to the function. The main objective is to grab any number from the passed in array and add them together with an empty array returning 0.
function totalNums(person) {
person.reduce((a,b) => a + b, 0)
return person.age;
}
console.log(totalNums([]))
You need to save the result into a new variable then console.log() it like this
const arr= [{ name: 'Clarie', age: 22 },
{ name: 'Bobby', age: 30 },
{ name: 'Antonio', age: 40 },...
];
function totalNums(person) {
let res = person.reduce((a,b) => a + b.age, 0)
return res;
}
console.log(totalNums(arr));
and this is why it has to be like that
.reduce()
js methods like .map(), .filter(), .reduce() and some others, they return a new array, they don't modify the original array.
You can console.log(arr); and you will get this output:
[{ name: 'Clarie', age: 22 },
{ name: 'Bobby', age: 30 },
{ name: 'Antonio', age: 40 },...
];
Your original array unchanged even after running your function so in order to get the result you expect, you need to store it inside a new variable
You need to save the result of your reduce.
For example with array of numbers you would do:
function totalNums(person) {
let res = person.reduce((a,b) => a + b, 0)
return res;
}
console.log(totalNums([5,6,4]))
And for your example you would like to do something like this:
function totalNums(person) {
let res = person.reduce((a,b) => a + b.age, 0)
return res;
}
console.log(totalNums([
{ name: 'Clarie', age: 22 },
{ name: 'Bobby', age: 30 },
{ name: 'Antonio', age: 40 }
]))
function totalNums(person) {
person.reduce((a,b) => a + b, 0)
return person.age;
}
console.log(totalNums([]))
Talking about the function you have created it is incorrect because:
return person.age; Here you are passing an array to function and then accessing it like it's an object.
person.reduce((a,b) => a + b, 0) you can't add a and b because b is an object.
You are not storing value which reduce function will return.
Solution Below :
The reduce function always returns something It never makes changes in the original array.
function totalNums(persons) {
const totalAge = persons.reduce((total, person) => total + person.age, 0);
return totalAge;
}
const persons = [
{ name: "Clarie", age: 22 },
{ name: "Bobby", age: 30 },
{ name: "Antonio", age: 40 },
];
console.log(totalNums(persons));
You can replace total and person with a and b respectively in the above code snippet for your reference.

Adding values to an object within an Array inside a FOR loop

I have an array extracted from Mongo in the following form
[
{
_id: 60d51d210e5e4e297066132a,
MemberName: 'Name of Member',
MemberRank: 25,
MemberFDR: 6.43,
MemberImageurl: 'uploads/images/gauravverma.jpg'
},
{
_id: 60d5c619c163f23195e01d00,
MemberName: 'Name Of Member',
MemberRank: 24,
MemberFDR: 6.5,
MemberImageurl: 'uploads/images/shashikhanna.jpeg'
},
]
After extracting the original array, I am looping through the array, extracting the name of the member and then doing some more queries in the DB. The length of this returned query, is the count and I want to add it in the original object like so
[
{
_id: 60d51d210e5e4e297066132a,
MemberName: 'Name of Member',
MemberRank: 25,
MemberFDR: 6.43,
MemberImageurl: 'uploads/images/gauravverma.jpg',
Count: 3(whatever the length of the array will be)
},
{
_id: 60d5c619c163f23195e01d00,
MemberName: 'Name Of Member',
MemberRank: 24,
MemberFDR: 6.5,
MemberImageurl: 'uploads/images/shashikhanna.jpeg'
Count: 5(whatever the length of the array will be)
},
]
My query returns the value perfectly, I am struggling with how to insert the value in the original object.
let memberName
let countOfCurrentChallengeMatches
for(let i=0; i<challengeList.length; ){
console.log("hi i am here 1")
memberName = challengeList[i].MemberName
console.log(memberName)
try {
console.log(memberName)
countOfCurrentChallengeMatches = await MatchRegister.find({
$and: [
{ $or: [{ChallengingPlayer: memberName},{ChallengedPlayer: memberName}] },
{ $or: [{ChallengeStatus: 'Awaiting Score Approval'},{ChallengeStatus: 'Accepted'},{ChallengeStatus: 'Completed'}, {ChallengeStatus: 'Issued'}] },
{ChallengerMonth: cMonth},
],
},'_id ChallengingPlayer ChallengedPlayer ChallengerMonth ChallengerYear ProposedChallengeDate ProposedChallengeTime ChallengeMatchLocation ChallengeStatus MatchFormat RejectionReason')
.sort({ProposedChallengeDate: 1}).exec()
} catch (err) {
const error = new HttpError(
'Something went wrong, could not update member.',
500
);
return next(error);
}
// Here is where i want to insert the value in the object
i++
}
I have tried options like, push, add and a few other options from google, but nothing works.
Just example below. Have you tried this example yet?
var arrOfObj = [{
name: 'eve'
}, {
name: 'john'
}, {
name: 'jane'
}];
var result = arrOfObj.map(function(el) {
var o = Object.assign({}, el);
o.isActive = true;
return o;
})
console.log(arrOfObj);
console.log(result);
Hey this simple line worked. Not sue why I missed it in my research
challengeList[i].count = countOfCurrentChallengeMatches.length

javascript [Object] inside my object instead of real data

I have the following js code https://repl.it/N0xy/0
I am trying to push some objects into an existing one using some functions:
mylist.push(createMyObject(item.name, item.school, item.teacher))
the result contains :
{ result: true, count: 1, items: [ [ [Object], [Object] ] ] }
instead of :
{ result: true, count: 1, items: [ { name: 'Jacky', school: 'high', teacher: 'good' },
{ name: 'Tom', school: 'college', teacher: 'bad' } ] }
how can i fix this?
thanks
You forgot to do JSON.stringify(obj) in the last statement. Everything else seems fine.
You might want to change the second last line to:
obj.items = create(); as well.
or maybe obj.items = obj.items.concat(create());
You pushed an array to obj.items in stead of the separate items. create() returns an array.
Try this:
create().forEach(function(item) {
obj.items.push(item);
});
OR
let createdItems = create();
for(item of createdItems) {
obj.items.push(item);
}
In your console.log at the end, wrap the obj in a call to JSON.stringify like this:
console.log("print my obj: ",obj);

Convert string to nested array

I have a string passed from server which was called with AJAX and I have to convert the string into a nested array which will be used to populate on PDF.
For example:
var tableData = "[{ name: 'Bartek', age: 34 },{ name: 'John', age: 27 },{ name:'Elizabeth', age: 30 }]";
and I need to convert into an array in JavaScript which will be like this:
var newTableData = [
{ name: 'Bartek', age: 34 },
{ name: 'John', age: 27 },
{ name: 'Elizabeth', age: 30 }
];
How can I do that?
As pointed out in the comments, the best solution would be to return a valid JSON from the server and to parse it using JSON.parse.
You can use tools like https://jsonlint.com/ or JSV to check that your JSON is valid.
If because of some "real world problem", your servers aren't JSON complaint, you can use a dirty parser like dirty-json or write your own JSON parse.
dirty-json does not require object keys to be quoted, and can handle single-quoted value strings.
var dJSON = require('dirty-json');
dJSON.parse("{ test: 'this is a test'}").then(function (r) {
console.log(JSON.stringify(r));
});
// output: {"test":"this is a test"}
Your last resort, while technically possible and the easiest to implement, is probably your worst choice because of it's dangers. but it would work out of the box: eval.
eval(tableData);
// [ { name: 'Bartek', age: 34 },
// { name: 'John', age: 27 },
// { name: 'Elizabeth', age: 30 } ]
By slightly changing how you return the string from the server you can JSON.parse it
var dataString = '[{"name":"Bartek","age":34},{"name":"John","age":27},{"name":"Elizabeth","age":30}]';
var data = JSON.parse(dataString);
console.log(data);
Use eval() method The completion value of evaluating the given code. If the completion value is empty, undefined is returned:
var tableData = "[{ name: 'Bartek', age: 34 },{ name: 'John', age: 27 },{ name:'Elizabeth', age: 30 }]";
tableData = eval(tableData);
console.log(tableData[0]);

Compare value and add if matches to an array

Im trying to merge 2 data sources in 1, I wanna loop through them and if a specefic value matches than add it to the first object with the same value and add the in the emty array what is already there. No matter how much objects I have.
So lets say I have this information
Source 1
one = {
"teams": [
{
name: 'ABC',
members: [],
rooms: '0'
},
{
name: 'DEF',
members: [],
rooms: '1'
}
]
}
Source 2
two = {
"persons": [
{
name: 'Foo',
gender: 'male',
room: '1'
},
{
name: 'Bar',
gender: 'female',
room: '2'
}
]
}
And what I want is that the 'persons' array merge to the members array if the 'room and rooms' value matches.
What I would assume is something similar like this:
for(var i = 0 ; i < two.persons.length; i++) {
if (one.teams[i].rooms == two.persons[i].room) {
data.teams[i].members.push(two.persons[i]);
}
}
using higher order methods you can do:
one = {
"teams": [
{
name: 'ABC',
members: [],
rooms: '0'
},
{
name: 'DEF',
members: [],
rooms: '1'
}
]
};
two = {
"persons": [
{
name: 'Foo',
gender: 'male',
room: '1'
},
{
name: 'Bar',
gender: 'female',
room: '2'
}
]
};
var ttt = one.teams.map(function(x){
var roomVal= x.rooms;
x.members = two.persons.filter(function(t){
return t.room == roomVal});
return x;
})
one.teams = ttt;
console.log(one)
The problem with your code is that once you iterate the two array, then you do not go back and see if the previous element matched with the current one.
For example, if [0] on each arrays does not match and you iterate to index [1] in the for-loop, you do not have a way to check if two[1] matched one[0].
To do a complete search, you could directly iterate the arrays for each value of two:
two.persons.forEach(function(person) {
one.teams.forEach(function(team) {
if (team.rooms == person.room) {
team.members.push(person);
}
});
});
There are many strategies to do this. But most important you should iterate each array separately. I would use an Array.forEach();
one.teams.forEach(function (team, teamsIndex, teamsArray) {
two.persons.forEach(function (person, personsIndex, personsArray) {
if (team.room == person.room) {
// Do what you need to do.
}
});
});
Didn't check syntax so be aware to read Array.forEach(); documentation.

Categories