Issue returning result from a function - javascript

Hi I cannot return information from a function? When I try I always receive an 'undefined' message.
When I console.log the variables within the function the information appears to be correct.
The purpose of the function is to add sales data for an employee to the employee object.
This is what should happen -
{
id: 3,
firstName: 'Fred',
lastName: 'Jones',
gender: 'Non-Binary',
age: 54,
position: 'Salesperson',
sales: [{
staffId: 3,
item: 'Pre-built PC',
price: 1999.95,
date: '02-09-2022'
},
{
staffId: 3,
item: 'USB Cable',
price: 5,
date: '02-09-2022'
},
{
staffId: 3,
item: 'HDMI Cable',
price: 15.45,
date: '02-09-2022'
}
]
}
This is the function that I have -
function mapEmpAndSales() {
employeesData.map(function(employee) {
let newEmpInfo = Object.assign({}, employee);
// console.log("1");
// console.log(newEmpInfo.id);
newEmpInfo.sales = salesData.filter(function(element) {
return element.staffId == employee.id;
});
// console.log("2");
// console.log("XXXXXXXX");
// console.log(newEmpInfo);
return newEmpInfo;
// result = newEmpInfo;
});
// console.log(result);
// return result;
}
const finalresult = mapEmpAndSales();
// let newInfo = mapEmpAndSales();
console.log("XXXXXXX");
console.log(finalresult);

This line:
// return result;
is necessary to pass data back out through your function. It should not be commented out. But I don't think you want to return result, rather return employeesData variable.
return employeesData;

Your mapEmpAndSales didn't return any thing, you need return the value of employeesData.map(...).
function mapEmpAndSales() {
return employeesData.map(function(employee) {
// ....
});
}

I think is because you aren't returning in the function 'mapEmpAndSales', if you see your return is inside the 'function(employee){...}'. So, you create this function 'function(employee)' and return in that, but in the body of your main function have no return.
Try creating a const outside the map function like 'const result = []', and in your map function you add the result at it and in your main function your really return the result.
Like this:
function mapEmpAndSales() {
const result = [];
employeesData.map(function(employee) {
let newEmpInfo = Object.assign(Object.assign({}, employee));
newEmpInfo.sales = salesData.filter(function(element) {
return element.staffId == employee.id;
});
result.push(...newEmpInfo); // IF IT RETURNS A ARRAY
result.push(newEmpInfo); //IF IT RETURNS ONLY ONE VALUE
});
return result;
}

The map function returns an array, which should be captured ad returned from the mapEmpAndSales function.
The solution is already in your code, just simply uncommenting the //return result; line as the following:
function mapEmpAndSales() {
let result = employeesData.map(function(employee) {
let newEmpInfo = Object.assign({}, employee);
newEmpInfo.sales = salesData.filter(function(element) {
return element.staffId == employee.id;
});
return newEmpInfo;
});
return result;
}
const finalresult = mapEmpAndSales();
console.log(finalresult);

Related

I am trying to make a function which will return an id from array of object

I want to write a function which will return id from array of object but when i call that function it returns me what I pass.
export function getRecipeByID(requestId) {
recipes.find(function (recipe) {
return recipe.id === requestId;
});
return requestId;
}
for example I call function
getRecipeByID(1)
and it returns 1.
I guess what you want to write is this:
export function getRecipeByID(requestId) {
return recipes.find(function (recipe) {
return recipe.id === requestId;
});
}
Notice that it doesn't return requestId but the result of recipes.find()
That's because you return requestId in your method while what you want is to return the result of recipes.find...
export function getRecipeByID(requestId) {
return recipes.find(function (recipe) {
return recipe.id === requestId;
});
}
you return requestId after using find which cause issue
const recipes = [
{
id: 2,
name: 'pasta'
},
{
id: 3,
name: 'sandwich'
},
{
id: 4,
name: 'pizza'
}
]
function getRecipeById(requestId) {
const findRecipe = recipes.find(function (recipe) {
return recipe.id === requestId;
});
return findRecipe;
}
console.log(getRecipeById(2)); // it will return{ id:2, name:"pasta" }
Try this:
export function getRecipeByID(requestId) {
const recipe = recipes.find(item => item.id === requestId);
if (recipe && recipe.id) {
return recipe.id;
} else {
return null;
}
}
Explanation: You're not assigning the result of the find operation (the element that has been found or null if there was no matching element) to any variable and are simply returning the request id.
Also: I'd suggest you'd look into arrow functions. They have been available for some years now and make your code much easier to read. :)
If you really want a function that return the same Id that you fetch, then do it:
export function getRecipeByID(requestId) {
return requestId;
}
otherwise, if want to fetch an Object of your list of object then you can simply try:
const array1 = [{}]
export function getRecipeByID(requestId) {
return array1.find(element => element.id == requestId);
}

How to pass data from one function to another function that is an argument of the first function

In the below example, when using getData();, is it possible to access the data contained in its object map within a new function – ie. useData(); – that is an argument of getData();?
const getData = (useData) => {
const myData = {
0: { title: 'Hello' },
1: { title: 'World!' }
};
Object.keys(myData).map((item) => {
useData();
});
}
getData(console.log(
/**
* Somehow access data represented by `myData` and `item`
* in above object map along the lines of `myData[item].title`
*/
));
Do you want to achieve something like that?
You can call useData with some arguments inside map function. You can't call some function like console.log as argument to getData function in this case.
const getData = useData => {
const myData = {
0: { title: "Hello" },
1: { title: "World!" },
};
Object.keys(myData).map(item => {
useData(myData[item]);
});
};
getData(console.log);
Yes, that is the default behaviour. But you need to pass a function(console.log) instead of a function invocation(console.log()) and invoke it only later.
const getData = (useData) => {
const myData = {
0: { title: 'Hello' },
1: { title: 'World!' }
};
Object.keys(myData).map((item) => {
useData.apply(console, [item]);
useData.apply(console, [ myData[item].title ]);
//or useData(myData[item].title)
});
}
getData(console.log);
getData(console.log('something'));
is same as:
let x = console.log('something');
getData(x);

Testing RxJS using TestScheduler with Promises and angular

I'm having a small issue using RxJS and Angular (not Angular 2) that I'm sure indicates I'm just doing something wrong, but I'm not sure exactly what.
I have a function that creates an rx.Observable stream that I would like to test. A simplified version of the function is below:
ResourceCollection.prototype.rxFetch = function() {
var scheduler = this.injectedScheduler;
var result = functionThatReturnsAnObservable(theseParams).concatMap(function(items) {
var promises = _.map(readFromExternal(items), function(promise) {
// results of this promise should be ignored
return Rx.Observable.fromPromise(promise, scheduler);
});
promises = promises.concat(_.map(items, function(item) {
// callEvent returns EventResult, these values should be passed on
return Rx.Observable.fromPromise(callEvent(item), scheduler);
}));
return promises;
}).concatMap(function(x) { return x; }).filter(function(res) {
return (res instanceOf EventResult);
}).toArray();
return result;
});
My test function looks like this:
describe('query', function() {
var customers;
var scheduler;
beforeEach(function() {
scheduler = new Rx.TestScheduler();
customers = new ResourceCollection({
url: '/api/customers',
keyName: 'CustomerId',
globalActions: {
rxQuery: { method: 'GET', isArray: true }
}
});
$httpBackend.whenGET('/api/customers/rxQuery').
respond(function() {
return [200, [
{ CustomerId: 1, Name: 'Brian', Region: 'North' },
{ CustomerId: 2, Name: 'Ravi', Region: 'East' },
{ CustomerId: 3, Name: 'Ritch', Region: 'East' },
{ CustomerId: 4, Name: 'Jeff', Region: 'West' },
{ CustomerId: 5, Name: 'Brandon', Region: 'West' }
]];
});
});
it('rxFetch customers', function(done) {
var vals;
customers.injectedScheduler = scheduler
var result = customers.rxFetch();
result.subscribe(function(values) {
vals = values;
});
$httpBackend.flush();
// my question is here - what can I do to get rid of this loop?
while (vals == null) {
scheduler.advanceBy(100);
$rootScope.$apply();
}
scheduler.start();
expect(vals.length).toEqual(5);
expect(vals[0]).toBe(customers[0]);
done();
});
});
The issue is a simple one - while the while loop in the test is in there, the test will produce the correct results (which is an array that contains the results of all the callEvent functions). Replace the while loop with a scheduler.scheduleAbsolute (or some other such call) combined with a $rootScope.$apply, and only one of the promises from the callEvent function will complete. Call it twice, and two of them will complete, etc (hence the while loop).
But the while loop is pretty ugly - and I'm sure there has to be an cleaner way to get this test to pass. Many thanks to anyone who can point me in the correct direction.

foreach loop and returning value of undefined

I was wondering if anyone could explain me why this function return undefined instead of founded object
var people = [
{name: 'John'},
{name: 'Dean'},
{name: 'Jim'}
];
function test(name) {
people.forEach(function(person){
if (person.name === 'John') {
return person;
}
});
}
var john = test('John');
console.log(john);
// returning 'undefined'
Returning into forEach loop won't work, you are on the forEach callback function, not on the test() function. So instead you need to return the value from outside the forEach loop.
var people = [{
name: 'John'
}, {
name: 'Dean'
}, {
name: 'Jim'
}];
function test(name) {
var res;
people.forEach(function(person) {
if (person.name === 'John') {
res = person;
}
});
return res;
}
var john = test('John');
console.log(john);
Or for finding a single element from array use find()
var people = [{
name: 'John'
}, {
name: 'Dean'
}, {
name: 'Jim'
}];
function test(name) {
return people.find(function(person) {
return person.name === 'John';
});
}
var john = test('John');
console.log(john);
You have two possibilities
A result set with Array#filter():
// return the result set
function test(name) {
return people.filter(function(person){
return person.name === 'John';
});
}
or a boolean value if the given name is in the array with Array#some():
// returns true or false
function test(name) {
return people.some(function(person){
return person.name === 'John';
});
}

How to return value in promise javascript

I have some issue with my code. I need to return a value in promise but don't know how to achived that. I'm newbie in ECS6
Following is my createDate function:
var createData = function (i, object) {
return new Promise(function(resolve) {
var item = object[i]
handleDiease(item.disease).then(function (diseaseId) {
handleCountry(item.country).then(function (countryId) {
handleStatus(lodash.capitalize(item['status(no/failed attempt/yes/friend)'])).then(function (statusId) {
handleType(lodash.capitalize(item["type(o/p)"])).then(function (typeId) {
ContactBLL.create({
name: item.name,
organisation: item.organisation,
email: item.email,
phonenumbers: item.phone,
facebook_url: item.facebook_url,
contactdate: item.date,
da_name: item.donation_affiliate_name,
da_url: item.donation_affiliate_url,
article_url: item.article_url,
//isparticipatefacp: item.isparticipatefacp,
survey_id: item.survey,
notes: item.notes,
fbcontact_diseaseid: diseaseId,
fbcontact_countryid: countryId,
lk_contactstatusid: statusId,
lk_contacttypeid: typeId,
}).then(function (rs) {
if (i < object.length - 2) createData(i + 1, object)
else {
**In else case, i want to return value, i'm using resolve(true) or return true but bold of them not work**
}
});
})
})
})
})
})
}
Following is where I use createDate function:
createData(0, json).then(function(rs) {
console.log(rs)
**It not console anything because I think createData not return or resolve anything**
})
You need to chain your promises, each then should return the promise inside it. Also, avoid explicit construction:
var createData = function (i, object) {
var item = object[i]
var desease = handleDiease(item.disease); // make all requests
var country = handleCountry(item.country); // concurrently, no need to wait
var stat = handleStatus(lodash.capitalize(item['status(no/failed attempt/yes/friend)']));
var type = handleType(lodash.capitalize(item["type(o/p)"]))
// join aggregates several promises, notice the `return` here.
return Promise.join(desease, country, stat, type,
function(deseaseId, countryId, statusId, typeId) {
return ContactBLL.create({ // this needs a `return` too
name: item.name,
organisation: item.organisation,
email: item.email,
phonenumbers: item.phone,
facebook_url: item.facebook_url,
contactdate: item.date,
da_name: item.donation_affiliate_name,
da_url: item.donation_affiliate_url,
article_url: item.article_url,
//isparticipatefacp: item.isparticipatefacp,
survey_id: item.survey,
notes: item.notes,
fbcontact_diseaseid: diseaseId,
fbcontact_countryid: countryId,
lk_contactstatusid: statusId,
lk_contacttypeid: typeId,
});
})
.then(function (rs) { // chain the promise
if (i < rs.length - 2) return createData(i + 1, rs);
else return true;
});
};

Categories