I want to remove square bracket "[ ]" in json object or concatenate some array of object to one array of object.
This code for counting current stock
currentStock : ( req, res, next) => {
var listed_item = _(arr_items).map( (z) => {
var result = module.exports.getTransactionAfterDate(z.created_at, z.item_id);
return result;
})
var jsonContent = JSON.stringify(listed_item);
return res.send(jsonContent);
},
getTransactionAfterDate : (date, item_id) => {
var result = _(db_transaction).filter( (x) => {
return x.created_at > date && x.item_id == item_id;
});
return result;
}
this is "listed_item" json result
[
[{
"id": 30608,
"item_id": "A01001",
"quantity": 150,
"status": "OUT",
"created_at": "2020-02-10 16:11:51",
}],
[],
[{
"id": 30412,
"item_id": "A02001",
"quantity": 53,
"status": "OUT",
"created_at": "2020-02-06 14:44:20",
}, {
"id": 30482,
"item_id": "A02001",
"quantity": 33,
"created_at": "2020-02-07 15:26:50",
"updated_at": "2020-02-07 15:26:50",
}]
]
what i want is like this
[
{
"id": 30608,
"item_id": "A01001",
"quantity": 150,
"status": "OUT",
"created_at": "2020-02-10 16:11:51",
},
{
"id": 30412,
"item_id": "A02001",
"quantity": 53,
"status": "OUT",
"created_at": "2020-02-06 14:44:20",
}, {
"id": 30482,
"item_id": "A02001",
"quantity": 33,
"created_at": "2020-02-07 15:26:50",
"updated_at": "2020-02-07 15:26:50",
}
]
note
i tried concatenate "getTransactionAfterDate" inside "arr_items" map to join all array inside
var temp = [];
var listed_item = _(arr_items).map( (z) => {
temp = _(temp).concat(module.exports.getTransactionAfterDate(z.created_at, z.item_id));
var result = temp;
return result;
})
but the result is empty array
[ [], [], [] ]
Try this
currentStock : ( req, res, next) => {
var items = [];
_(arr_items).forEach( (z) => {
var result = module.exports.getTransactionAfterDate(z.created_at, z.item_id);
result.forEach( item => {
items.push(item);
}
})
var jsonContent = JSON.stringify(items);
return res.send(jsonContent);
},
You can 'flatten' the array with lodash, which will just merge all the arrays into a single one:
_(arr).flatten()
That should then give you a single array of your objects, with no empty arrays either.
.flatten() in the lodash docs here: https://lodash.com/docs/#flatten
So it would be something like this (edited based on comments):
currentStock : ( req, res, next) => {
var listed_item = _(arr_items).map( (z) => {
var result = module.exports.getTransactionAfterDate(z.created_at, z.item_id);
return result;
})
var flattened = _(listed_item).flatten();
var jsonContent = JSON.stringify(flattened);
return res.send(jsonContent);
},
Nice and simple! (if I correctly understood what you are trying to do :-)
this can be done with the combination of _.flatten (for this lodash is required) and Array.prototype.filter like shown below
let newArray = _.flatten(listed_item.filter(e => e.length > 0))
Related
I want to scan dynamodb using filter on product_id showing in below json of table.
Can anybody explain how to do scanning using filter of product_id.
Wants to scan dynamodb table data using documentclient.
Wants to find all fields which has product_id: something
{
"mandi_id": 1,
"product": [
{
"updated_price": 24,
"product_id": 2,
"last_price": 23
},
{
"updated_price": 24,
"product_id": 5,
"last_price": 23
}
],
"status": "active",
"createdAt": "2022-04-21T08:23:41.774Z",
"mandiCloseTime": "4pm",
"mandi_description": "anaj mandi",
"mandi_name": "gaziabad anaj mandi",
"state": "uttar pradesh",
"city": "gaziabad",
"main_image_s3": "",
"mandi_latlong": {
"lng": 77.48325609999999,
"lat": 28.680346
},
"mandiOpenTime": "10am",
"updatedAt": "2022-04-21T08:23:41.774Z",
"address_name": "gavindpuram",
"landmark_name": "mandi",
"village": "gaziabad",
"postal": "201013"
}
I have tried the following set of code but it is returning empty array list
var params = {
TableName: "dev-agrowave-mandi-management",
// Select: "ALL_ATTRIBUTES"
FilterExpression: "contains(#product,:product)",
ExpressionAttributeNames: {
"#product": "product",
},
ExpressionAttributeValues: { ":product": {"product_id":parseInt(id)}
}
};
let lastEvaluatedKey = 'dummy'; // string must not be empty
const itemsAll = [];
while (lastEvaluatedKey) {
const data = await docClient.scan(params).promise();
itemsAll.push(...data.Items);
lastEvaluatedKey = data.LastEvaluatedKey;
if (lastEvaluatedKey) {
params['ExclusiveStartKey'] = lastEvaluatedKey;
}
}
return {msg:itemsAll,params:params};
I have a JSON response structure like this
{
"_id": "620e97d76ca392a43097cca6",
"user": "620295cbd67ece90802d2522",
"orderId": "EnrL7C",
"Items": [
{
"product": {
"name": "Fresh Salad",
"id": "61f2911723ff35136c98ad3e"
},
"quantity": 1,
"price": 1250,
"_id": "620e97d76ca392a43097cca7"
},
],
}
But i want the product not to be an object, so it should look like this
{
"_id": "620e97d76ca392a43097cca6",
"user": "620295cbd67ece90802d2522",
"orderId": "EnrL7C",
"Items": [
{
"name": "Fresh Salad",
"id": "61f2911723ff35136c98ad3e",
"quantity": 1,
"price": 1250,
"_id": "620e97d76ca392a43097cca7"
},
],
}
This is my code responsible for the response output
exports.getOrder = (req,res) => {
Order.findOne({orderId: 'EnrL7C'})
.populate("Items.product", "name")
.exec((error, order) => {
if(error) return res.status(400).json({ error });
if (order) {
return res.json(order);
}else{
return res.json(['No order found']);
}
});
Sometimes when I'm too lazy to look up all the mongoose documentation and figure out what version I'm on etc, I use the .lean() to just convert it to a normal JS object, which I'm way more comfortable with.
exports.getOrder = (req, res) => {
Order.findOne({ orderId: "EnrL7C" })
.lean() // add lean
.populate("Items.product", "name")
.exec((error, order) => {
if (error) return res.status(400).json({ error });
if (order) {
// fix the structure in javascript
order.Items = order.Items.map((item) => {
const flat = {
...item.product,
...item,
};
delete flat.product;
return flat;
});
return res.json(order);
} else {
return res.json(["No order found"]);
}
});
};
Let me know if that doesn't work, so I can update the answer.
I'm trying to update the values of my payments array objects
{
"balance": 109610,
"gifts": [],
"orders": [],
"payments": [{
"isPaid": 0,
"status": "Pending",
"address": "3KsdQbmADyz1KNN7qqX1yZcMXBbfFCm31r",
"date": 1624057559970
}, {
"isPaid": 0,
"status": "Pending",
"address": "3FYQK6YiAaL8fEbDWaXYw38CJN3K2y5dPD",
"date": 1624058531601
}],
"isVendedor": false,
"isAdmin": true,
"createdAt": {
"$date": "2021-06-17T21:10:15.020Z"
},
"username": "teste",
"email": "teste#teste.com",
"password": "$2a$10$qUNkorDuvbf.AYLTvjNc4ebKyNgLa7L9NoTBwAIV8.BfN51umaD9O",
"__v": 3
}
First, I look for the object of the user who made a request to my server
const userPayment = await User.find({"payments.address": notification.address}).exec();
Then I go through the user object and find it until I find the position where I find notification.address again
userPayment.forEach((AllPayments, index) => {
AllPayments.payments.forEach((payment, index) => {
if (payment.address == notification.address) {
if (payment.isPaid || payment.status != "Pending")
return res.json({
success: false,
error: "Payment Already Processed!",
});
const valueToDeposit = Math.round(notification.fiat_amount);
console.log(
userPayment[0].payments[index].isPaid,
userPayment[0].payments[index].status
);
// Set payments[index].isPaid = true
// Set payments[index].status = "Paid"
});
});
So I tried to make these 3 ways and none of them was successful.
userPayment[0].balance += valueToDeposit; // this works when save() is triggered
userPayment[0].payments[index].isPaid = 1; // this doesnt works when save() is triggered
userPayment[0].payments[index].status = "Paid"; // this doesnt works when save() is triggered
userPayment[0].updateOne({"payments.address": notification.address}, { $set: { "payments.$.isPaid": 1,"payments.$.status":"Paid" } },(err, result) => { console.log(err, result); }); this doesnt works
userPayment[0].save()
I use PostgreSQL with Sequelize. I have one templates table that has one column named location and its type is JSONB.
userLocationIds is an array of Location. I wrote a function that want to filter the template as its Location that the value of it should be included userLocationIds.
But when I run get empty array. How can I solve it?
This is my code:
export const getList = async (oId, userId) => {
const userLocationIds = await UserLocation.findAll({
where: { userId: userId},
attributes:["locationId"]
}).map((location) => {
return location.locationId
})
const templatesList = await Templates.findAll({
where: { oId , location: { [Op.in]: userLocationIds }},
})
return templatesList
}
my template is like:
[
{
"id": 10,
"templateName": "test",
"orgId": "7549",
"location": [
1,
316,
317
],
"items": null,
"templateType": "cxxred",
},
{
"id": 11,
"templateName": "test2",
"orgId": "7549",
"location": [
2
316,
327
],
"items": null,
"templateType": "cxxred",
}]
I am trying to get count of unseen messages from object in lodash.
below is my object
[
"conversation_id": "5a88779b2321141f2864e484"
"messages": [
{
"message_id": "5a88779b2321141f2864e483",
"sender_uid": 2,
"receiver_uid": 1,
"created": "2018-02-17T18:42:35.252Z",
"status": 1,
"delivered": false,
"seen": true,
}
]
]
I want to get count of seen: false messages
You can use filter to get all see = false messages and then can check length
var users = {
"conversation_id": "5a88779b2321141f2864e484",
"messages": [
{ "message_id": "5a88779b2321141f2864e483","sender_uid": 2,"receiver_uid": 1,"created": "2018-02-17T18:42:35.252Z","status": 1,"delivered": false,"seen": true,},
{ "message_id": "5a88779b2321141f2864e483","sender_uid": 2,"receiver_uid": 1,"created": "2018-02-17T18:42:35.252Z","status": 1,"delivered": false,"seen": false },
{ "message_id": "5b88779b2321141f2864e483","sender_uid": 2, "receiver_uid": 1, "created": "2018-02-17T18:42:35.252Z", "status": 1,"delivered": false,"seen": false,}
]
}
var unseen_messages = _.filter(users.messages, message => { return !message.seen; }).length;
console.log(unseen_messages);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>
Without lodash you can use reduce
var users = {
"conversation_id": "5a88779b2321141f2864e484",
"messages": [
{ "message_id": "5a88779b2321141f2864e483","sender_uid": 2,"receiver_uid": 1,"created": "2018-02-17T18:42:35.252Z","status": 1,"delivered": false,"seen": true,},
{ "message_id": "5a88779b2321141f2864e483","sender_uid": 2,"receiver_uid": 1,"created": "2018-02-17T18:42:35.252Z","status": 1,"delivered": false,"seen": false },
{ "message_id": "5b88779b2321141f2864e483","sender_uid": 2, "receiver_uid": 1, "created": "2018-02-17T18:42:35.252Z", "status": 1,"delivered": false,"seen": false,}
]
}
items = users.messages;
var totalCount = items.reduce((total, obj) => { return (!obj.seen) ? (total +1) : total }, 0);
console.log(totalCount);
_.sumBy would do the trick
const unseenMessages = _.sumBy(users.messages, message => message.seen === false);