Format JSON data into nested list using Lodash - javascript

I am new to lodash, and I have difficulty in formatting data that will display on an expanded table. I have a response of data from the server that looks like this:
[{Day: 1, ItemName: "Item1", Total: 1, Details: "Brand X", Quantity: 5, Part: "Part A"}]
And I wanted it to look like this:
[{
Day: 1,
ItemName: "Item1",
Total: 1,
ItemDetails: [{
Details: "Brand X",
Quantity: 5,
ItemParts: [{
Part: "Part A"
}]
}]
}]
I've used .chain and .GroupBy function and it displays on a table that shows the Day, ItemName and Total rows. Used .map function so when the user clicks the table row it expands and shows the ItemDetails.
But unfortunately i dont know how to display the last row or the third nested json data(which is ItemParts) that expands also when the user clicks the ItemDetails.
P.S. You can use any lodash function but please format the data to look like in the description above
P.S.S I only want to format JSON data response, I dont want to modify anything from my table

Something like this without lodash,
const arr = [{
Day: 1,
ItemName: "Item1",
Total: 1,
Details: "Brand X",
Quantity: 5,
Part: "Part A"
}]
const result = arr.map(x => ({
Day: x.Day,
ItemName: x.ItemName,
Total: x.Total,
ItemDetails: [{
Details: x.Details,
Quantity: x.Quantity,
ItemParts: [{
Part: x.Part
}]
}],
}))
console.log(result)

Related

Change the positive number to negative number in array of object

Given array of object in database:
detail : [
0: {
Code: "Code 1",
Price: "1.00",
IncTaxPrice: "1.20",
Tax:"0.20",
},
1: {
Code: "Code 2",
Price: "9.00",
IncTaxPrice: "9.20",
Tax:"0.20",
}
]
Output i want with key and value negative (for eg)
[
{
Code: "Code 1",
Price: "-1.00",
IncTaxPrice: "-1.20",
Tax: "-0.20",
},
{
Code: "Code 2",
Price: "-9.00",
IncTaxPrice: "-9.20",
Tax: "-0.20",
},
];
I tried with the map, filter function but it gave an error I guess I am missing something.
After it filters properly I will use -Math.abs(), to convert positive to negative.
let final = detail.map(a => Object.values(a).filter(v => typeof v === 'number'))
the element like price,tax are something like 8 different elements of numbers and amounts.
Thanks for #VLAZ suggestion in the comment. I think you can filter by the key using Object.keys().
Example below:
const detail = [
{
Code: "Code 1",
Price: "1.00",
IncTaxPrice: "1.20",
Tax: "0.20",
},
{
Code: "Code 2",
Price: "9.00",
IncTaxPrice: "9.20",
Tax: "-0.20",
},
];
let final = detail.map(x => ({
Code: x.Code,
Price: -Number(x.Price),
IncTaxPrice: -Number(x.IncTaxPrice),
Tax: -Number(x.Tax),
}));
console.log(final);
You should wrap your 0, 1 indexes in curly brackets as it is an array of objects. You can't just define it as you did because indexes 0 and 1 are not just numbers (fex. [0,1,2] is valid but not [0:{code:...},1:{code:...}] They are contining an object inside, so they are objects and you can't map if your array of objects is not properly defined as:
[{0:{code:..}},{1:{code:..}}.
Also using typeof filter wont' work because all values are type string.
I would go like this:
let detail = [ {
0: {
Code: "Code 1",
Price: "1.00",
IncTaxPrice: "1.20",
Tax:"0.20",
}},
{1: {
Code: "Code 2",
Price: "9.00",
IncTaxPrice: "9.20",
Tax:"0.20",
}}
]
detail.map(el=>{
el[Object.keys(el)[0]]['Price']=(-parseFloat(el[Object.keys(el)[0]]['Price'])).toString()
el[Object.keys(el)[0]]['IncTaxPrice']=(-parseFloat(el[Object.keys(el)[0]]['IncTaxPrice'])).toString()
el[Object.keys(el)[0]]['Tax']=(-parseFloat(el[Object.keys(el)[0]]['Tax'])).toString()
return
}
)

Nested arrays with objects, lodash meanBy

Can someone please help me understand how to make this work. Everytime I feel like I start to understand arrays and objects in Javascript it turns out that I still don't.
I'm trying to get the average of all prices in the following datastructure by using lodash meanBy
[
{
date: "2019-12-17",
items: [
{ id: "1", state: "accepted", price: "90.5" },
{ id: "2", state: "rejected", price: "20.0" },
{ id: "3", state: "open", price: "10.5" },
]
},
{
date: "2019-12-18",
items: [
{ id: "4", state: "open", price: "450.0" },
{ id: "5", state: "rejected", price: "40.1" },
{ id: "6", state: "accepted", price: "50.9" },
]
}
]
If you provide the answer, can you also please try to explain how you select something nested in items, because that's as far as I get before I get lost.
In this case instead of selecting nested values, it's easier to flatten the items to a single array, and then apply _.meanBy(). In addition, the prices are strings, and not numbers, so you'll need to convert them.
Flatten the items to a single array with Array.flatMap(), and then use _.meanBy(), and get the numeric values of the prices:
const data = [{"date":"2019-12-17","items":[{"id":"1","state":"accepted","price":"90.5"},{"id":"2","state":"rejected","price":"20.0"},{"id":"3","state":"open","price":"10.5"}]},{"date":"2019-12-18","items":[{"id":"4","state":"open","price":"450.0"},{"id":"5","state":"rejected","price":"40.1"},{"id":"6","state":"accepted","price":"50.9"}]}]
const result = _.meanBy(_.flatMap(data, 'items'), o => +o.price)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
Another approach is to get the general average, by getting the average of each items array separately , and then getting the average of all averages.
const data = [{"date":"2019-12-17","items":[{"id":"1","state":"accepted","price":"90.5"},{"id":"2","state":"rejected","price":"20.0"},{"id":"3","state":"open","price":"10.5"}]},{"date":"2019-12-18","items":[{"id":"4","state":"open","price":"450.0"},{"id":"5","state":"rejected","price":"40.1"},{"id":"6","state":"accepted","price":"50.9"}]}]
const result = _.meanBy(data, ({ items }) => _.meanBy(items, o => +o.price))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

Combine 2 different javascript json objects into one with a loop and joining on the questionid ,

So I am trying to combine 2 different javascript object than I can end up using in an angularjs ng-repeat . since there is a 1 to many relationship from the database, I was pulling queries separately.
What I have is this:
Main list of data , 3 object sample
0: Object
$$hashKey: "object:4"
Active:true
QuestionId:2
SalesChannel:"DTD"
1: Object
$$hashKey: "object:5"
Active:true
QuestionId:3
SalesChannel:"DTD"
2: Object
$$hashKey: "object:6"
Active:true
QuestionId:5
SalesChannel:"DTD"
Then another query returned data into what I want to relate as JSON into the other object
Object { Id: 3, Name: "Text box" QuestionId: 3}
{ Id: 4, Name: "Text box" QuestionId: 3}
{ Id: 9, Name: "Text box" QuestionId: 5}
So since I have both of these objects , I am wanting to combine.
Naturally I would think that I should return from the database, but then I also think about looping over and appending
for loop on main
{
.... find where main.QuestionId = sub.QuestionId and it to be added in as a nested object of json type...
Thus the end result SHOULD look like
[{
Active:true,
QuestionId: 3
SubData: [ {
Id: 3,
Name: "TextBox
QuestionId:3
},
{
Id: 4,
Name: "TextBox
QuestionId:3
}],
SalesChannel: "DTD"
}]
// and so on
How can i achieve this?
You want to go through all of the main objects, and assign to them only those results from second query. Use Array.prototype.forEach to go through them all, and Array.prototype.filter to select only appropriate results from secondary query.
firstQueryResult.forEach((firstObject)=>
firstObject.subdata = secondQueryResult.filter((secondObject)=>
secondObject.QuestionId === firstObject.QuestionId))
BTW, this has nothing to do with angularjs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

how get data within particular period using dates in angular2?

Hi I have certain amount data related to a customer. I need to get period of transactions of a customer and show to angular2 app.
I have one page with drop down list and output area. In dropdown items are like "Last one month transactions", "Last Three months transactions" and etc.
When I select a one of the item in dropdown I need show the all transactions in output area.
I am unable filter data using the pipes in angular2. Please send your thoughts about it. Thanks in advance.
[{
productNo:1,
productName: 'Toys',
quantity: 2,
purchaseDate: '2016/17/08'
},
{
productNo:1,
productName: 'Shoes',
quantity: 4,
purchaseDate: '2016/30/07'
},
{
productNo:1,
productName: 'Books',
quantity: 10,
purchaseDate: '2016/07/06'
},
{
productNo:1,
productName: 'Mobile',
quantity: 1,
purchaseDate: '2016/21/06'
}]

Insert array of objects into MongoDB

I wonder how I could insert array of objects to Mongo collection "root-level documents" with own pre-defined _id values.
I have tried db.MyCollection.insert(array); but it creates nested documents under one single generated _id in MongoDB.
var array = [
{ _id: 'rg8nsoqsxhpNYho2N',
goals: 0,
assists: 1,
total: 1 },
{ _id: 'yKMx6sHQboL5m8Lqx',
goals: 0,
assists: 1,
total: 1 }];
db.MyCollection.insert(array);
What I want
db.collection.insertMany() is what you need (supported from 3.2):
db.users.insertMany(
[
{ name: "bob", age: 42, status: "A", },
{ name: "ahn", age: 22, status: "A", },
{ name: "xi", age: 34, status: "D", }
]
)
output:
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("57d6c1d02e9af409e0553dff"),
ObjectId("57d6c1d02323d119e0b3c0e8"),
ObjectId("57d6c1d22323d119e0b3c16c")
]
}
Why not iterate over the array objects, and insert them one at a time?
array.forEach((item) => db.MyCollection.insert(item));
Go through this Link To get Exact Outcome the way you want:
https://docs.mongodb.org/manual/tutorial/insert-documents/#insert-a-document
You can use MongoDB Bulk to insert multiple document in one single call to the database.
First iterate over your array and call the bulk method for each item:
bulk.insert(item)
After the loop, call execute:
bulk.execute()
Take a look at the refereed documentation to learn more.

Categories

Resources