Create Object Array in foreach Javascript - javascript

I have an Array with these values, I need to create a loop on these values to return in alasql like this example:
http://jsfiddle.net/agershun/11gd86nx/5/
var data = {
"business": [
{
"order_contents": [
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 85,
"name": "product 3",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 84,
"name": "product 2",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 83,
"name": "product 1",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
},
{
"id": 84,
"name": "product 2",
"price": "1.99",
"quantity": 1,
"total": "1.99",
"ingredients": [],
"extras": []
}
]
}
]
};
here's my code..
info.orderByChild("data").startAt("08/04/2017").endAt("12/06/2017").on('value', function(snapshot){
snapshot.forEach(function(item) {
jsonObj = {
"business": [
{
"order_contents": [
{
"id": itemVal['id'],
"name": itemVal['name'],
"price": itemVal['price'],
"quantity": itemVal['quantity'],
"total": "itemVal['total']
}
]
}
]
}
its not creating an array, only the last value..
can someone help me?

You have to define your array in the beginning and add each object to it later on in your loop:
var result = { business: [] }; // PLACEHOLDER
var jsonObj;
info.orderByChild("data").startAt("08/04/2017").endAt("12/06/2017").on('value', function(snapshot) {
snapshot.forEach(function(item) {
jsonObj = {
"order_contents": [
{
"id": itemVal['id'],
"name": itemVal['name'],
"price": itemVal['price'],
"quantity": itemVal['quantity'],
"total": "itemVal['total']
}
]
};
result.business.push(jsonObj); // ADDING EACH OBJECT TO YOUR ARRAY
});
});

You want to map the items in snapshot to a new array, so instead of using the forEach method, use the map method and the resulting array it returns:
jsonObj = snapshot.map(function(item) {
return {
"business": [
{
"order_contents": [
{
"id": item['id'],
"name": item['name'],
"price": item['price'],
"quantity": item['quantity'],
"total": item['total']
}
]
}
]
}
});

Related

Perform array treatment with reduce

I have an array that i need to treat to extract and form a new object, this is the code i run right now:
data_proces = Object.values(selectedData.reduce((r, { Code, Description, Price}) => {
r[Description] ??= { Code, Description, Units: 0, Price: 0 , Total: 0};
r[Description].Code= Code;
r[Description].Units++;
r[Description].Price = Price ;
r[Description].Total += Price ;
return r;
}, {}));
This gives me:
[{
"Code": 0,
"Description": "No Factured Act",
"Units": 2,
"Price": 0,
"Total": 0
},
{
"Code": 1,
"Description": "Autopsy",
"Units": 1,
"Price": 44,
"Total": 44
},
{
"Code": 2,
"Description": "Simple Biopsy",
"Units": 3,
"Price": 29,
"Total": 87
},
{
"Code": 1,
"Description": "Citology",
"Units": 4,
"Price": 15,
"Total": 60
},
{
"Code": " -",
"Description": "Free Act",
"Units": 2,
"Price": 56789,
"Total": 91356
}]
And this is the result i want:
[{
"Code": 0,
"Description": "No Factured Act",
"Units": 2,
"Price": 0,
"Total": 0
},
"Code": 0,
"Description": "No Factured Act",
"Units": 1,
"Price": 0,
"Total": 0
},
{
"Code": 1,
"Description": "Autopsy",
"Units": 1,
"Price": 44,
"Total": 44
},
{
"Code": 2,
"Description": "Simple Biopsy",
"Units": 3,
"Price": 29,
"Total": 87
},
{
"Code": 1,
"Description": "Citology",
"Units": 4,
"Price": 15,
"Total": 60
},
{
"Code": " -",
"Description": "Free Act",
"Units": 1,
"Price": 34567,
"Total": 34567
},
{
"Code": " -",
"Description": "Free Act",
"Units": 1,
"Price": 56789,
"Total": 56789
}]
As you can see, i need "No Factured Act" and "Free Act" to NOT sum up their units and stay as an individual values, how can i achieve this with Reduce?.
You can simply create an array of Description properties that you don't want summed and create unique keys if the iterated description is included in the array. Here using the third index parameter of the reduce() callback.
const selectedData = [{ "Code": 0, "Description": "No Factured Act", "Price": 0, }, { "Code": 0, "Description": "No Factured Act", "Price": 0, }, { "Code": 1, "Description": "Autopsy", "Price": 44, }, { "Code": 2, "Description": "Simple Biopsy", "Price": 29, }, { "Code": 2, "Description": "Simple Biopsy", "Price": 29, }, { "Code": 2, "Description": "Simple Biopsy", "Price": 29, }, { "Code": 1, "Description": "Citology", "Price": 15, }, { "Code": 1, "Description": "Citology", "Price": 15, }, { "Code": 1, "Description": "Citology", "Price": 15, }, { "Code": 1, "Description": "Citology", "Price": 15, }, { "Code": " -", "Description": "Free Act", "Price": 34567, }, { "Code": " -", "Description": "Free Act", "Price": 56789, }];
const noSum = ['No Factured Act', 'Free Act'];
const data_process = Object.values(
selectedData.reduce((r, { Code, Description, Price }, i) => {
let key = Description;
if (noSum.includes(key)) {
key = `${key}_${i}`;
}
r[key] ??= { Code, Description, Units: 0, Price, Total: 0 };
r[key].Units++;
r[key].Total += Price;
return r;
}, {})
);
console.log(data_process);

Grouping nested arrays data by specific key

I have array list as follow:
let data =[
{
"id": "05a87dssff-7468-49b1-bae3-0cd06dc22189",
"details": [
[
{
"Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2",
"qty": 4,
"name": "chicken burger",
"price": 15,
"total": "60.00",
}
]
],
},
{
"id": "05a87dff-746gf-49b1-bae3-s0cd06dc22189",
"details": [
[
{
"Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2",
"qty": 4,
"name": "chicken burger",
"price": 15,
"total": "60.00",
}
]
],
},
{
"id": "06129f89-dd80-49dd-bf5d-a12764c23949",
"details": [
[
{
"Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2",
"qty": 4,
"name": "Beef burger",
"price": 15,
"total": "60.00",
}
],
[
{
"Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2",
"qty": 4,
"name": "Beef burger",
"price": 15,
"total": "60.00",
}
],
[
{
"Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2",
"qty": 4,
"name": "chicken burger",
"price": 15,
"total": "60.00",
}
]
],
}
]
I am trying to group all the arrays that have same name and then sum the values of the properties that have the same name in one grand total,
so the expected result based on the above array is:
[{'name':'chicken burger', 'total': 180},{'name':'Beef burger', 'total': 120}]
What i have tried is the following however, it keeps giving me the all array separated not grouped,
here is what i have done so far:
data.map(a => a.details.map(b => b.reduce((d,e)=> {
const newArr = d;
if (d.length && d[d.length - 1]['name'] === e['name'])
newArr[d.length - 1] =
{
//...d[d.length - 1], ...e,
total: parseFloat(d[d.length - 1].d) + parseFloat(e.total),
}
else newArr[d.length] = { ...e }
console.log(newArr)
return newArr;
},[]) ) );
and here a link to the code
Iterate over the array, using Map to store calculated sum.
let data =[ { "id": "05a87dssff-7468-49b1-bae3-0cd06dc22189", "details": [ [ { "Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2", "qty": 4, "name": "chicken burger", "price": 15, "total": "60.00", } ] ], }, { "id": "05a87dff-746gf-49b1-bae3-s0cd06dc22189", "details": [ [ { "Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2", "qty": 4, "name": "chicken burger", "price": 15, "total": "60.00", } ] ], }, { "id": "06129f89-dd80-49dd-bf5d-a12764c23949", "details": [ [ { "Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2", "qty": 4, "name": "Beef burger", "price": 15, "total": "60.00", } ], [ { "Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2", "qty": 4, "name": "Beef burger", "price": 15, "total": "60.00", } ], [ { "Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2", "qty": 4, "name": "chicken burger", "price": 15, "total": "60.00", } ] ] }];
const map = new Map();
data.forEach(
item => item.details.forEach(
detail => {
const {name, total} = detail[0];
map.has(name) ? map.get(name).total += +total : map.set(name, {name, total: +total})
}
)
);
const result = [...map.values()];
console.log(result);
You can use Array.prototype.map() to get the names and totals from the all the details arrays.
Then, use Array.prototype.reduce() in order to group the names.
let data = [
{
"id": "05a87dssff-7468-49b1-bae3-0cd06dc22189",
"details": [
[
{
"Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2",
"qty": 4,
"name": "chicken burger",
"price": 15,
"total": "60.00",
}
]
],
},
{
"id": "05a87dff-746gf-49b1-bae3-s0cd06dc22189",
"details": [
[
{
"Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2",
"qty": 4,
"name": "chicken burger",
"price": 15,
"total": "60.00",
}
]
],
},
{
"id": "06129f89-dd80-49dd-bf5d-a12764c23949",
"details": [
[
{
"Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2",
"qty": 4,
"name": "Beef burger",
"price": 15,
"total": "60.00",
}
],
[
{
"Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2",
"qty": 4,
"name": "Beef burger",
"price": 15,
"total": "60.00",
}
],
[
{
"Id": "6741c8b3-03bb-4431-9975-df25eae0a5c2",
"qty": 4,
"name": "chicken burger",
"price": 15,
"total": "60.00",
}
]
],
}
]
const namesAndTotals = data.flatMap(item => item.details.flat().map(({ name, total }) => ({ name, total: Number(total) })));
const res = Object.values(namesAndTotals.reduce((acc, { name, total }) => {
if(!acc[name]) {
acc[name] = {
name,
total
}
} else {
acc[name].total += total;
}
return acc;
}, {}));
console.log(res);

Using angularjs forEach loops

I am getting this type of json in my $scope of angularjs:
$scope.someStuff = {
"id": 2,
"service": "bike",
"min": "22",
"per": "100",
"tax": "1",
"categoryservices": [
{
"id": 32,
"category": {
"id": 1,
"name": "software"
}
},
{
"id": 33,
"category": {
"id": 2,
"name": "hardware"
}
},
{
"id": 34,
"category": {
"id": 3,
"name": "waterwash"
}
}
]
}
I want to use angularjs forEach loop and i want to get only category name,
My expected output:
[{"name":"software"}, {"name":"hardware"}, {"name":"waterwash"}]
You can use Array.map()
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
$scope.someStuff.categoryservices.map((x) => { return { name: x.category.name}})
var obj = {
"id": 2,
"service": "bike",
"min": "22",
"per": "100",
"tax": "1",
"categoryservices": [{
"id": 32,
"category": {
"id": 1,
"name": "software"
}
},
{
"id": 33,
"category": {
"id": 2,
"name": "hardware"
}
},
{
"id": 34,
"category": {
"id": 3,
"name": "waterwash"
}
}
]
};
console.log(obj.categoryservices.map((x) => {
return {
name: x.category.name
}
}))
You can use map method by passing a callback function as parameter.
const someStuff = { "id": 2, "service": "bike", "min": "22", "per": "100", "tax": "1", "categoryservices": [ { "id": 32, "category": { "id": 1, "name": "software" } }, { "id": 33, "category": { "id": 2, "name": "hardware" } }, { "id": 34, "category": { "id": 3, "name": "waterwash" } } ] }
let array = someStuff.categoryservices.map(function({category}){
return {'name' : category.name}
});
console.log(array);

How to find all unique paths in tree structure

root1
child1
child2
grandchild1
grandchild2
child3
root2
child1
child2
grandchild1
greatgrandchild1
I have an object array like tree structure like above, I want to get all unique paths in like this
Food->Dry Food Items->Local Dry Food Items
Food->Dry Food Items->Thai Dry Food Items
Food->Dry Food Items->Others
Food->Fruits
------
------
This is my object
[
{
"id": 1,
"name": "Food",
"parent_id": 0,
"children": [
{
"id": 5,
"name": "Dry Food Items",
"parent_id": 1,
"children": [
{
"id": 11,
"name": "Local Dry Food Items",
"parent_id": 5
},
{
"id": 12,
"name": "Thai Dry Food Items",
"parent_id": 5
},
{
"id": 60,
"name": "Others",
"parent_id": 5
}
]
},
{
"id": 6,
"name": "Fruits",
"parent_id": 1
},
{
"id": 7,
"name": "LG Branded",
"parent_id": 1
},
{
"id": 8,
"name": "Meat",
"parent_id": 1
},
{
"id": 9,
"name": "Sea food",
"parent_id": 1
},
{
"id": 10,
"name": "Vegetables",
"parent_id": 1,
"children": [
{
"id": 14,
"name": "Local Vegetables",
"parent_id": 10
},
{
"id": 15,
"name": "Thai Vegetables",
"parent_id": 10
}
]
},
{
"id": 38,
"name": "Frozen",
"parent_id": 1
},
{
"id": 39,
"name": "IP Kitchen",
"parent_id": 1,
"children": [
{
"id": 40,
"name": "IP Meat",
"parent_id": 39
},
{
"id": 41,
"name": "IP Starter",
"parent_id": 39
},
{
"id": 42,
"name": "IP Ingredients",
"parent_id": 39
},
{
"id": 43,
"name": "IP Sauce",
"parent_id": 39
},
{
"id": 44,
"name": "IP Seafood",
"parent_id": 39
},
{
"id": 45,
"name": "IP Starter",
"parent_id": 39
},
{
"id": 46,
"name": "IP Desert",
"parent_id": 39
}
]
}
]
},
{
"id": 2,
"name": "Beverage",
"parent_id": 0,
"children": [
{
"id": 16,
"name": "Bar",
"parent_id": 2
},
{
"id": 17,
"name": "Coffee & Tea",
"parent_id": 2
},
{
"id": 18,
"name": "In Can",
"parent_id": 2
},
{
"id": 19,
"name": "Water",
"parent_id": 2
},
{
"id": 47,
"name": "IP Bar",
"parent_id": 2
}
]
},
{
"id": 3,
"name": "Disposable",
"parent_id": 0,
"children": [
{
"id": 21,
"name": "Disposable",
"parent_id": 3
}
]
},
{
"id": 4,
"name": "SOE",
"parent_id": 0,
"children": [
{
"id": 20,
"name": "Cleaning Materials",
"parent_id": 4
},
{
"id": 22,
"name": "Chinaware",
"parent_id": 4
}
]
}
];
I get to all the nodes in the tree
function traverse(categories) {
categories.forEach(function (category) {
if (category.children && category.children.length) {
traverse(category.children);
}
else {
}
}, this);
}
You can use recursion and create a function using forEach loop.
var arr = [{"id":1,"name":"Food","parent_id":0,"children":[{"id":5,"name":"Dry Food Items","parent_id":1,"children":[{"id":11,"name":"Local Dry Food Items","parent_id":5},{"id":12,"name":"Thai Dry Food Items","parent_id":5},{"id":60,"name":"Others","parent_id":5}]},{"id":6,"name":"Fruits","parent_id":1},{"id":7,"name":"LG Branded","parent_id":1},{"id":8,"name":"Meat","parent_id":1},{"id":9,"name":"Sea food","parent_id":1},{"id":10,"name":"Vegetables","parent_id":1,"children":[{"id":14,"name":"Local Vegetables","parent_id":10},{"id":15,"name":"Thai Vegetables","parent_id":10}]},{"id":38,"name":"Frozen","parent_id":1},{"id":39,"name":"IP Kitchen","parent_id":1,"children":[{"id":40,"name":"IP Meat","parent_id":39},{"id":41,"name":"IP Starter","parent_id":39},{"id":42,"name":"IP Ingredients","parent_id":39},{"id":43,"name":"IP Sauce","parent_id":39},{"id":44,"name":"IP Seafood","parent_id":39},{"id":45,"name":"IP Starter","parent_id":39},{"id":46,"name":"IP Desert","parent_id":39}]}]},{"id":2,"name":"Beverage","parent_id":0,"children":[{"id":16,"name":"Bar","parent_id":2},{"id":17,"name":"Coffee & Tea","parent_id":2},{"id":18,"name":"In Can","parent_id":2},{"id":19,"name":"Water","parent_id":2},{"id":47,"name":"IP Bar","parent_id":2}]},{"id":3,"name":"Disposable","parent_id":0,"children":[{"id":21,"name":"Disposable","parent_id":3}]},{"id":4,"name":"SOE","parent_id":0,"children":[{"id":20,"name":"Cleaning Materials","parent_id":4},{"id":22,"name":"Chinaware","parent_id":4}]}]
function getNames(data) {
var result = [];
function loop(data, c) {
data.forEach(function (e) {
var name = !c.length ? e.name : c + '->' + e.name;
if (e.children) { loop(e.children, name); }
else {
result.push({ name: name });
}
});
}
loop(data, '');
return result;
}
console.log(getNames(arr))

How to return childobject property from json with lodash?

I am using lodash and have this json object, the property I would like to return is a nested array ie swappableProducts:
{
"existing": {
"hasPlatinum": false,
"primaryBundle": {
"id": "2008",
"serviceId": "1",
"name": "TV - Entertainment, Sport",
"products": [
{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false
},
{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false,
"swappableProducts": [
{
"name": "Movies",
"id": "105",
"price": 2000,
"gifted": false
},
{
"name": "Games",
"id": "10",
"price": 1000,
"gifted": false
}
]
}
]
}
}
I tried to return the swappableProducts array like this:
_.get(userObject, 'existing.primaryBundle.products[1].swappableProducts');
but it won't return it. How can I do this?

Categories

Resources