I have a set of data. I map through my data, if data is "HOME_DELIVERY then it will go to another function which will check is the order is valid or not. if the order is valid then it will return hello string. So far everything works as expected but I want my map function return string hello. currently it's returning ['hello']
const getRoundName = (orderId) => {
if (orderId === "a4013438-926f-4fdc-8f6a-a7aa402b40ea") {
return "hello";
} else {
retrun
}
};
const orders = [
{
id: "a4013438-926f-4fdc-8f6a-a7aa402b40ea",
modifiedAt: "2022-02-28T09:26:18+00:00",
deliveryDate: "2022-02-28",
pickupLocation: null,
orderStatus: "MODIFIED",
deliverySlotId: "2022-02-28:66ee337c-e252-4297-9aed-cafcef396f19",
createdAt: "2022-02-26T06:38:46+00:00",
deliveryTime: "22-00",
storeId: "516079340",
orderNumber: 28354107,
paymentMethod: "ON_DELIVERY",
cartItems: [[Object], [Object], [Object]],
deliveryMethod: "HOME_DELIVERY",
additionalInfo: null,
},
];
const roundName = orders.map((order) => {
return order.deliveryMethod === 'HOME_DELIVERY' ? getRoundName(order.id) : ''
});
console.log(roundName);
Array.map returns an array as response. If you need a string as response, you have to modify the logic as
const getRoundName = (orderId) => {
if (orderId === "a4013438-926f-4fdc-8f6a-a7aa402b40ea") {
return "hello";
} else {
return;
}
};
const orders = [
{
id: "a4013438-926f-4fdc-8f6a-a7aa402b40ea",
modifiedAt: "2022-02-28T09:26:18+00:00",
deliveryDate: "2022-02-28",
pickupLocation: null,
orderStatus: "MODIFIED",
deliverySlotId: "2022-02-28:66ee337c-e252-4297-9aed-cafcef396f19",
createdAt: "2022-02-26T06:38:46+00:00",
deliveryTime: "22-00",
storeId: "516079340",
orderNumber: 28354107,
paymentMethod: "ON_DELIVERY",
cartItems: [[Object], [Object], [Object]],
deliveryMethod: "HOME_DELIVERY",
additionalInfo: null,
},
{
id: "a4013438-926f-4fdc-8f6a-a7aa402b40ef",
modifiedAt: "2022-02-28T09:26:18+00:00",
deliveryDate: "2022-02-28",
pickupLocation: null,
orderStatus: "MODIFIED",
deliverySlotId: "2022-02-28:66ee337c-e252-4297-9aed-cafcef396f19",
createdAt: "2022-02-26T06:38:46+00:00",
deliveryTime: "22-00",
storeId: "516079340",
orderNumber: 28354107,
paymentMethod: "ON_DELIVERY",
cartItems: [[Object], [Object], [Object]],
deliveryMethod: "HOME_DELIVERY",
additionalInfo: null,
},
];
const roundName = orders.flatMap((order) => {
return order.deliveryMethod === 'HOME_DELIVERY' ? getRoundName(order.id) : ''
});
console.log(roundName.join(''));
You can use filter before calling map
//if it has more than 1 items in the list, it will join them together like this `hellohellohello`
const orderIds = orders.filter((order) => order.deliveryMethod === 'HOME_DELIVERY').map(order => getRoundName(order.id)).join("")
Related
I have a service that is in charge of bringing the tickets with the last message of the users.
For this, the Contact, Queue, WhatsApp models were added to the include.
The problem is that when adding the Tags model, closely related to "Contact", the service stopped working and response with:
"Unknown column 'contact.name' in where clause
The only thing I added was the relationship with Tags, since it is new. Help me understand? It's like it no longer recognizes the column
interface Request {
searchParam?: string;
pageNumber?: string;
status?: string;
date?: string;
showAll?: string;
userId: string;
withUnreadMessages?: string;
queueIds: number[];
}
interface Response {
tickets: Ticket[];
count: number;
hasMore: boolean;
}
const ListTicketsService = async ({
searchParam = "",
pageNumber = "1",
queueIds,
status,
date,
showAll,
userId,
withUnreadMessages
}: Request): Promise<Response> => {
let whereCondition: Filterable["where"] = {
[Op.or]: [{ userId }, { status: "pending" }],
queueId: { [Op.or]: [queueIds, null] }
};
let includeCondition: Includeable[];
includeCondition = [
{
model: Contact,
as: "contact",
attributes: ["id", "name", "number", "profilePicUrl"],
include: [{
model: Tags,
as: "tags",
attributes: ["name"],
}]
},
{
model: Queue,
as: "queue",
attributes: ["id", "name", "color"]
},
{
model: Whatsapp,
as: "whatsapp",
attributes: ["name"]
},
];
if (showAll === "true") {
whereCondition = { queueId: { [Op.or]: [queueIds, null] } };
}
if (status) {
whereCondition = {
...whereCondition,
status
};
}
if (searchParam) {
const sanitizedSearchParam = searchParam.toLocaleLowerCase().trim();
includeCondition = [
...includeCondition,
{
model: Message,
as: "messages",
attributes: ["id", "body"],
where: {
body: where(
fn("LOWER", col("body")),
"LIKE",
`%${sanitizedSearchParam}%`
)
},
required: false,
duplicating: false
}
];
whereCondition = {
...whereCondition,
[Op.or]: [
{
"$contact.name$": where(
fn("LOWER", col("contact.name")),
"LIKE",
`%${sanitizedSearchParam}%`
)
},
{ "$contact.number$": { [Op.like]: `%${sanitizedSearchParam}%` } },
{
"$message.body$": where(
fn("LOWER", col("body")),
"LIKE",
`%${sanitizedSearchParam}%`
)
}
]
};
}
if (date) {
whereCondition = {
createdAt: {
[Op.between]: [+startOfDay(parseISO(date)), +endOfDay(parseISO(date))]
}
};
}
if (withUnreadMessages === "true") {
const user = await ShowUserService(userId);
const userQueueIds = user.queues.map(queue => queue.id);
whereCondition = {
[Op.or]: [{ userId }, { status: "pending" }],
queueId: { [Op.or]: [userQueueIds, null] },
unreadMessages: { [Op.gt]: 0 }
};
}
const limit = 40;
const offset = limit * (+pageNumber - 1);
const { count, rows: tickets } = await Ticket.findAndCountAll({
where: whereCondition,
include: includeCondition,
distinct: true,
limit,
offset,
order: [["updatedAt", "DESC"]], logging: console.log
});
const hasMore = count > offset + tickets.length;
return {
tickets,
count,
hasMore
};
};
export default ListTicketsService;
Another thing is, i don't know how but this is giving me only unique record. The problem is, 1 contact may have n Tags. So, its possible do this query?
Regards
I got stuck with this problem and don't know how to fix it. I set up the server side props and it's working on the terminal on vscode but when i inspect in chrome or try to do something with it well, nothing appears.
export const getServerSideProps = async (context) => {
try {
let properties = []
const propertiesRef = collection(firestore, 'properties')
const q = query(propertiesRef, orderBy("propertiename", "desc"))
onSnapshot(q, (snapshot) => {
properties.push(snapshot.docs.map((doc) => (
{ ...doc.data(), id: doc.id }
)))
console.log(properties)
});
return {
props: {
propertiesProps : properties,
}
}
} catch(error) {
console.log(error)
}
}
When i pass the data here in the page i dont get anything back
function index({propertiesProps}) {
const [properties, setProperties] = useState([])
useEffect(async () => {
setProperties( propertiesProps)
console.log(properties)
}, [])
return (
<div>
<Head>
<title>Rimoz | Properties</title>
</Head>
<h1 className="main">Heres is the list of properties</h1>
<PropertieGallery />
<h1 className="main">Com server side props</h1>
<p></p>
</div>
)
}
export default index
And this is what i get in the terminal on vscode
[
[
{
propertiename: 'casa 57',
photos: [Array],
id: 'lKOfK8oirnLY5DNEJagH'
},
{
propertiename: 'casa 56',
photos: [Array],
id: 'r1IRpreknf5Pd7FqRUqJ'
},
{
photos: [Array],
propertiename: 'casa 55',
id: 'H2ADAlP4dyuZJCsYNnor'
},
{
propertiename: 'casa 54',
photos: [Array],
id: 'dB8wHXjwFHGB3JoIIGQv'
},
{
propertiename: 'casa 4 ',
photos: [Array],
id: 'jApsE2wgxBpdbajuObgx'
},
{
propertiename: 'casa 3 ',
photos: [Array],
id: 'mrOJasIuHUXI5ojISSWD'
},
{
photos: [Array],
propertiename: 'casa 2',
id: 'rBOG1mXUewKYiH47MbdM'
},
{
photos: [Array],
propertiename: 'casa 14',
id: 'c3ozTup7m1ZWIjSSzh7v'
}
]
]
What am i missing here?
Currently receiving the error from my notnull validator, however I am passing defined variables through a new object that clearly have values. user, site, and contact are all associations, so im not sure if in my api route if im not to create the properties then just pass them from my post request, however since this is MySql I do believe that it is required, I could most certainly be wrong. Any help or insight would be greatly appreciated.
Api Route
console.log(req.body);
db.Case.create({
caseName: req.body.caseName,
userId: req.body.userId,
siteId: req.body.siteId,
contactId: req.body.contactId
}).then((response) => {
console.log(response);
res.json(response)
}).catch((err) => {
console.log(err);
})
})
Model
module.exports = (sequelize, DataTypes) => {
const Case = sequelize.define('Case', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
caseName: {
type: DataTypes.STRING,
allowNull: false,
},
createdAt: {
type: DataTypes.DATE
},
updatedAt: {
type: DataTypes.DATE,
},
})
Case.associate = (models) => {
Case.belongsTo(models.User, {
foreignKey : {
allowNull : false
}
})
Case.belongsTo(models.Site, {
foreignKey: {
allowNull: false
}
})
Case.belongsTo(models.Contact, {
foreignKey: {
allowNull : false
}
})
}
return Case;
}
post request
const caseName = $('#caseName');
const UserId = sessionStorage.getItem('id');
const SiteId = $('#insertSite').attr('id');
const ContactId = $('#insertContact').attr('id');
if(!caseName.val().trim() || !UserId || !SiteId || !ContactId){
console.log('Please enter all of the Case information')
return;
}
const newCase = {
caseName: caseName.val().trim(),
UserId: UserId,
SiteId: SiteId,
ContactId: ContactId,
};
console.log(newCase);
axios.post('/api/Case', newCase).then((res) => {
console.log('New Case has been added' + res);
}).catch((err) => {
console.log(err);
});
testing object that is being passed
{
caseName: 'tttttttttt',
UserId: '1',
SiteId: 'insertSite',
ContactId: 'insertContact'
}
Error Response
errors: [
ValidationErrorItem {
message: 'Case.UserId cannot be null',
type: 'notNull Violation',
path: 'UserId',
value: null,
origin: 'CORE',
instance: [Case],
validatorKey: 'is_null',
validatorName: null,
validatorArgs: []
},
ValidationErrorItem {
message: 'Case.SiteId cannot be null',
type: 'notNull Violation',
path: 'SiteId',
value: null,
origin: 'CORE',
instance: [Case],
validatorKey: 'is_null',
validatorName: null,
validatorArgs: []
},
ValidationErrorItem {
message: 'Case.ContactId cannot be null',
type: 'notNull Violation',
path: 'ContactId',
value: null,
origin: 'CORE',
instance: [Case],
validatorKey: 'is_null',
validatorName: null,
validatorArgs: []
}
]
}
The properties in your API create method are not capitalized properly.
caseName: req.body.caseName,
userId: req.body.userId,
siteId: req.body.siteId,
contactId: req.body.contactId
Both sides of the : for the 3 foreign keys need to have their capitalization fixed.
Considering the below object:
[
{
id: 5fc0be2990a8a12cc0ba0b5c,
projectName: 'E-271120-B',
projectManagaer: '5f7f1ba973ff621da4322248',
dataInici: 2020-11-26T23:00:00.000Z,
dataEntrega: 2020-11-26T23:00:00.000Z,
dtoGlobal: null,
dtoProjecte: null,
archived: false,
created: 2020-11-27T08:51:57.242Z,
updated: 2021-01-25T10:01:18.733Z
tabs: [{permissionsUserID:[250,8]},{permissionsUserID:[3]}],
__v: 3
},
{
tabs: [{permissionsUserID:[3,350]},{permissionsUserID:[15]}],
_id: 5fc0be4690a8a12cc0ba0b5f,
projectManagaer: '5f7f0e69b5862e1a085db388',
projectName: 'E-271120-C',
dataInici: 2020-11-27T23:00:00.000Z,
dataEntrega: 2020-11-29T23:00:00.000Z,
dtoGlobal: null,
dtoProjecte: null,
archived: false,
created: 2020-01-21T08:46:41.958Z,
updated: 2021-01-21T08:46:41.958Z,
__v: 2
},
{
tabs: [{permissionsUserID:[31,350]},{permissionsUserID:[8,893]}],
_id: 5fc0be4690a8a12cc0ba0b5f,
projectManagaer: '5f7f0e69b5862e1a085db388',
projectName: 'E-23410-C',
dataInici: 2020-11-27T23:00:00.000Z,
dataEntrega: 2020-11-29T23:00:00.000Z,
dtoGlobal: null,
dtoProjecte: null,
archived: false,
created: 2020-01-21T08:46:41.958Z,
updated: 2021-01-21T08:46:41.958Z,
__v: 2
}
]
Each object represents a Project. A project has many tabs.
I want to return only the projects that at least one tab contains in permissionsUserID the ID of the user that is logged.
So if the user that is logged has the ID 8, these are the projects I want to obtain:
[
{
id: 5fc0be2990a8a12cc0ba0b5c,
projectName: 'E-271120-B',
projectManagaer: '5f7f1ba973ff621da4322248',
dataInici: 2020-11-26T23:00:00.000Z,
dataEntrega: 2020-11-26T23:00:00.000Z,
dtoGlobal: null,
dtoProjecte: null,
archived: false,
created: 2020-11-27T08:51:57.242Z,
updated: 2021-01-25T10:01:18.733Z
tabs: [{permissionsUserID:[250,8]},{permissionsUserID:[3]}],
__v: 3
},
{
tabs: [{permissionsUserID:[31,350]},{permissionsUserID:[8,893]}],
_id: 5fc0be4690a8a12cc0ba0b5f,
projectManagaer: '5f7f0e69b5862e1a085db388',
projectName: 'E-23410-C',
dataInici: 2020-11-27T23:00:00.000Z,
dataEntrega: 2020-11-29T23:00:00.000Z,
dtoGlobal: null,
dtoProjecte: null,
archived: false,
created: 2020-01-21T08:46:41.958Z,
updated: 2021-01-21T08:46:41.958Z,
__v: 2
}
]
That's the filter I have done:
async getAll(pagination, user) {
try {
const filter = {};
if(pagination.archived) {
filter['archived'] = pagination.archived;
}
if(pagination.search) {
filter['$text'] = {$search: pagination.search}
}
const { Project: projectSchema } = this.getSchemas();
const projectsDocs = await projectSchema.paginate(filter, {
limit: pagination.limit ? parseInt(pagination.limit) : 10,
page: pagination.page ? parseInt(pagination.page) + 1 : 1
});
if (!projectsDocs) {
throw new errors.NotFound('No Projects.');
}
projectsDocs.docs.forEach(element => {
element.tabs.filter( d => d.permissionsUserID.every( c => c.includes(user._id)));
});
return projectsDocs;
} catch (error) {
throw error;
}
},
Here is one way
const data = [...];
const userId = 8;
const result = data.filter((item) => {
const {tabs} = item;
let loggedIn = false;
tabs.forEach((tab) => {
if (tab.permissionsUserID.includes(userId)) {
loggedIn = true;
return true
}
})
return loggedIn;
})
Here's a simple function which should get you what you want.
Filter() returns a subset of the projects list. Some() returns true if at least one of the tabs has the value we're looking for. Includes() returns true if the permissionsUserId list has the user id we want. Chain those together and you get the subset of projects where a tab's permissions has the desired user id.
const data = [
/* list of projects */
],
userId = 8;
function getProjectsForUserId (data, userId) {
return data.filter((project) => {
return project.tabs.some((tab) => {
return tab.permissionsUserID.includes(userId);
});
});
}
console.log(getProjectsForUserId(data, 8));
I have an array of JSON, config data.
var config = [ [{'state': 'step1'}],
[{'state': 'step2'}] ,
[{'state': 'step3'}]
];
In config, data are in ordered form.
I also have a JSON, Events data, which has these state but they are not in sequential order. I want to convert below Events data based on config.
Events: [
{ Status: 'rendered', State: 'step2' },
{ Status: 'rendered', State: 'step3' },
{ Status: 'rendered', State: 'step1' } ,
{ Status: 'completed', State: 'step3'}
],
Also, last step of config will have two entry and for that rendered state should come before completed.
Result that I am expecting is :
Events: [
{ Status: 'rendered', State: 'step1' },
{ Status: 'rendered', State: 'step2' },
{ Status: 'rendered', State: 'step3' } ,
{ Status: 'completed', State: 'step3' }
]
PS : I don't have any working/error prone code for this as of now. Basically I am not being able to think how to incorporate config for making changes in Events.
Thanks
Transform config into an array of strings, and then use .sort while comparing the difference in indexOf of the States property in that array:
var config = [ [{'state': 'step1'}],
[{'state': 'step2'}] ,
[{'state': 'step3'}]
];
const Events = [
{ Status: 'rendered', State: 'step2' },
{ Status: 'rendered', State: 'step3' },
{ Status: 'rendered', State: 'step1' } ,
{ Status: 'completed', State: 'step3'}
];
const eventOrders = config.map(([{ state }]) => state);
Events.sort((a, b) => (
eventOrders.indexOf(a.State) - eventOrders.indexOf(b.State)
|| Events.indexOf(a) - Events.indexOf(b)
));
console.log(Events);
You can do that in following steps
First convert array from config like ['step1','step2','step3']
Use sort() on events
Then sort the objects in events bases on indexOf() State property of item in the above array.
var config = [ [{'state': 'step1'}],
[{'state': 'step2'}] ,
[{'state': 'step3'}]
];
let states = config.map(x => x[0].state);
const events = [
{ Status: 'rendered', State: 'step2' },
{ Status: 'rendered', State: 'step3' },
{ Status: 'rendered', State: 'step1' } ,
{ Status: 'completed', State: 'step3'}
]
const res = events.sort((a,b) => states.indexOf(a.State) - states.indexOf(b.State));
console.log(res);
Added the logic to keep rendered before completed if State are same.
var config = [
[{'state': 'step1'}],
[{'state': 'step2'}],
[{'state': 'step3'}]
];
const Events = [
{ Status: 'rendered', State: 'step2' },
{ Status: 'completed', State: 'step3' },
{ Status: 'rendered', State: 'step1' } ,
{ Status: 'rendered', State: 'step3'}
];
const eventOrders = config.map( ([{state}]) => state);
Events.sort((a, b) => {
let result = eventOrders.indexOf(a.State) - eventOrders.indexOf(b.State);
if(result == 0){
if(a.Status=='rendered' && b.Status=='completed') return -1;
if(b.Status=='rendered' && a.Status=='completed') return 1;
return 0;
}
return result;
});
console.log(Events);
It works for me hope it helps you.
function arrangeOrder(arrNeedToArrange, accToArrange, keyOfarrNeedsToArrange, keyOfArrAccToArange) {
let arrangedArr = [];
accToArrange.map((val) => {
let res = arrNeedToArrange.filter(obj => { return obj[keyOfarrNeedsToArrange] == val[0][keyOfArrAccToArange] });
res.map(r => arrangedArr.push(r))
})
return arrangedArr;
}
function setAtLastToObj(arr, key, val) {
let lastObj = {};
arr = arr.filter((obj) => {
if (obj[key] == val) {
lastObj = obj;
}
return obj[key] != val
});
arr.push(lastObj);
return arr;
}
let arr = arrangeOrder(Events, config, 'State', 'state');
arr = setAtLastToObj(arr, 'Status', 'completed');