Perform array treatment with reduce - javascript

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);

Related

How to filter product data when checkbox selected is true in reactjs?

I have searched a lot regarding filter of product data using checkbox but couldn't able to find the right answer for my issue.
Problem: I'm making a product filter page using checkbox in react but could not found the proper way to filter the true value of object key.
ie. I have to only filter object key value === true. Below array object is after checkbox selection before the selection it will be falsy value.
const category = [
{
"type":"Color",
"options":[
{
"key":"Red",
"value":true
},
{
"key":"Blue",
"value":false
},
{
"key":"Green",
"value":true
}
]
},
{
"type":"Gender",
"options":[
{
"key":"Men",
"value":true
},
{
"key":"Women",
"value":false
}
]
},
{
"type":"Price",
"options":[
{
"key":"0 - Rs. 250",
"from":0,
"to":250,
"value":false
},
{
"key":"Rs. 251 - 450",
"from":251,
"to":450,
"value":true
},
{
"key":"Rs. 451 & above",
"from":451,
"to":"Number.MAX_VALUE",
"value":false
}
]
},
{
"type":"Type",
"options":[
{
"key":"Polo",
"value":false
},
{
"key":"Hoodie",
"value":false
},
{
"key":"Basic",
"value":true
}
]
}
]
const productData = [
{
"id": 1,
"name": "Black Polo",
"type": "Polo",
"price": 250,
"currency": "INR",
"color": "Black",
"gender": "Men",
"quantity": 3
},
{
"id": 2,
"name": "Blue Polo",
"type": "Polo",
"price": 350,
"currency": "INR",
"color": "Blue",
"gender": "Women",
"quantity": 3
},
{
"id": 3,
"name": "Pink Polo",
"type": "Polo",
"price": 350,
"currency": "INR",
"color": "Pink",
"gender": "Women",
"quantity": 6
},
{
"id": 4,
"name": "Black Hoodie",
"type": "Hoodie",
"price": 500,
"currency": "INR",
"color": "Black",
"gender": "Men",
"quantity": 2
},
{
"id": 5,
"name": "Green Polo",
"type": "Polo",
"price": 250,
"currency": "INR",
"color": "Green",
"gender": "Men",
"quantity": 1
},
{
"id": 6,
"name": "Green Polo",
"type": "Polo",
"price": 350,
"currency": "INR",
"color": "Green",
"gender": "Women",
"quantity": 1
},
{
"id": 7,
"name": "Blue Hoodie",
"type": "Hoodie",
"price": 500,
"currency": "INR",
"color": "Blue",
"gender": "Women",
"quantity": 2
},
{
"id": 8,
"name": "Black Hoodie",
"type": "Hoodie",
"price": 500,
"currency": "INR",
"color": "Black",
"gender": "Women",
"quantity": 5
}]
Now,I need filtered product data from the above category data and product-data.
Here's my Codesandbox link for this.

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);

how can i compare two multidimensional array and merge into single array

I am looking to find a way to compare and combine two multidimensinal array of objects based on course values. I can make it work using the filter method for the top level, but not sure how to make sure that all levelwithskills are deeply merged. Here is an example:
var array1 = [
{
"course": "Javascript and protractor",
"description": "this is test course",
"levelwithskills": [
{
"name": "Beginner",
"skills": [
{
"duration": 45,
"name": "HTML/CSS/JS",
"price": 75
},
{
"duration": 45,
"name": "Data And Flows",
"price": 75
},
{
"duration": 45,
"name": "Functions And Objects",
"price": 75
},
{
"duration": 45,
"name": "Protractor Project",
"price": 75
}
]
},
{
"name": "Improver",
"skills": [
{
"duration": 45,
"name": "Jasmine",
"price": 90
},
{
"duration": 45,
"name": "Protractor Methods",
"price": 90
},
{
"duration": 45,
"name": "Non Angular App Testing",
"price": 90
},
{
"duration": 45,
"name": "Reports",
"price": 90
}
]
},
{
"name": "Intermediate",
"skills": [
{
"duration": 45,
"name": "Crossbrowser Config",
"price": 100
},
{
"duration": 45,
"name": "Data-Driven",
"price": 100
},
{
"duration": 45,
"name": "Gulp-Integration",
"price": 100
},
{
"duration": 45,
"name": "User Stories To Test",
"price": 100
}
]
}
],
"s3key": "javascsipt.png"
},
{
"course": "Java and BDD",
"id": "564e0758-803f-11e9-ba30-01cdbe15a808",
"levelwithskills": [
{
"name": "Beginner",
"skills": [
{
"duration": 45,
"name": "HTML/CSS/JS",
"price": 1
},
{
"duration": 45,
"name": "Data and flows",
"price": 1
},
{
"duration": 45,
"name": "OOP",
"price": 1
},
{
"duration": 45,
"name": "Libraries",
"price": 1
}
]
},
{
"name": "Improver",
"skills": [
{
"duration": 45,
"name": "Selenium Webdriver",
"price": 90
},
{
"duration": 45,
"name": "Junit",
"price": 90
},
{
"duration": 45,
"name": "Saucelabs",
"price": 90
},
{
"duration": 45,
"name": "User Stories To Test",
"price": 90
}
]
},
{
"name": "Intermediate",
"skills": [
{
"duration": 45,
"name": "Most Used Methods",
"price": 100
},
{
"duration": 45,
"name": "Git",
"price": 100
},
{
"duration": 45,
"name": "Gherkin",
"price": 100
},
{
"duration": 45,
"name": "Cucumber",
"price": 100
}
]
},
{
"name": "Semi-Advance",
"skills": [
{
"duration": 45,
"name": "Maven",
"price": 110
},
{
"duration": 45,
"name": "Cucumber Data-driven",
"price": 11000
},
{
"duration": 45,
"name": "Jenkins",
"price": 110
},
{
"duration": 45,
"name": "Pipeline",
"price": 110
}
]
},
{
"name": "Advance",
"skills": [
{
"duration": 45,
"name": "Page Object Model",
"price": 120
},
{
"duration": 45,
"name": "Advanced Methods",
"price": 120
},
{
"duration": 45,
"name": "Advanced Logic",
"price": 120
},
{
"duration": 45,
"name": "Your Own Framework",
"price": 120
}
]
},
{
"name": "Professional",
"skills": [
{
"duration": 45,
"name": "Serenit Framework p1",
"price": 130
},
{
"duration": 45,
"name": "Serenit Framework p2",
"price": 130
},
{
"duration": 45,
"name": "Serenit Framework p3",
"price": 130
},
{
"duration": 45,
"name": "Serenit Framework p4",
"price": 130
}
]
}
],
"passion": "Tester",
"s3key": "java.png",
}
];
var array2 = [
{
"course": "Javascript and protractor",
"levelwithskills": [
{
"name": "Beginner",
"skills": [
{
"name": "HTML/CSS/JS"
}
]
}
]
}
,
{
"course": "Java and BDD",
"levelwithskills": [
{
"name": "Beginner",
"skills": [
{
"name": "HTML/CSS/JS"
}
]
}
]
}
];
const sameData = array1.map(
obj =>
array2.map(obj2 => {
if (obj.course === obj2.course) {
return {
...obj,
levelwithskills: obj.levelwithskills.map(
xlvl =>
obj2.levelwithskills.map(ylvl => {
if (xlvl.name === ylvl.name) {
return {
...xlvl,
skills: xlvl.skills.map(
xskill =>
ylvl.skills.map(yskill => {
if (xskill.name === yskill.name) {
return {
...xskill,
selected: true
};
}
return xskill;
})[0]
)
};
}
return xlvl;
})[0]
)
};
}
})[0]
);
console.log(sameData);
I am looking to take something like that and merge it like:
[
{
"course": "Javascript and protractor",
"description": "this is test course",
"levelwithskills": [
{
"name": "Beginner",
"skills": [
{
"duration": 45,
"name": "HTML/CSS/JS",
"price": 75,
"selected": true
},
{
"duration": 45,
"name": "Data And Flows",
"price": 75
},
{
"duration": 45,
"name": "Functions And Objects",
"price": 75
},
{
"duration": 45,
"name": "Protractor Project",
"price": 75
}
]
},
{
"name": "Improver",
"skills": [
{
"duration": 45,
"name": "Jasmine",
"price": 90
},
{
"duration": 45,
"name": "Protractor Methods",
"price": 90
},
{
"duration": 45,
"name": "Non Angular App Testing",
"price": 90
},
{
"duration": 45,
"name": "Reports",
"price": 90
}
]
},
{
"name": "Intermediate",
"skills": [
{
"duration": 45,
"name": "Crossbrowser Config",
"price": 100
},
{
"duration": 45,
"name": "Data-Driven",
"price": 100
},
{
"duration": 45,
"name": "Gulp-Integration",
"price": 100
},
{
"duration": 45,
"name": "User Stories To Test",
"price": 100
}
]
}
],
"s3key": "javascsipt.png"
},
{
"course": "Java and BDD",
"id": "564e0758-803f-11e9-ba30-01cdbe15a808",
"levelwithskills": [
{
"name": "Beginner",
"skills": [
{
"duration": 45,
"name": "HTML/CSS/JS",
"price": 1
"selected": true
},
{
"duration": 45,
"name": "Data and flows",
"price": 1
},
{
"duration": 45,
"name": "OOP",
"price": 1
},
{
"duration": 45,
"name": "Libraries",
"price": 1
}
]
},
{
"name": "Improver",
"skills": [
{
"duration": 45,
"name": "Selenium Webdriver",
"price": 90
},
{
"duration": 45,
"name": "Junit",
"price": 90
},
{
"duration": 45,
"name": "Saucelabs",
"price": 90
},
{
"duration": 45,
"name": "User Stories To Test",
"price": 90
}
]
},
{
"name": "Intermediate",
"skills": [
{
"duration": 45,
"name": "Most Used Methods",
"price": 100
},
{
"duration": 45,
"name": "Git",
"price": 100
},
{
"duration": 45,
"name": "Gherkin",
"price": 100
},
{
"duration": 45,
"name": "Cucumber",
"price": 100
}
]
},
{
"name": "Semi-Advance",
"skills": [
{
"duration": 45,
"name": "Maven",
"price": 110
},
{
"duration": 45,
"name": "Cucumber Data-driven",
"price": 11000
},
{
"duration": 45,
"name": "Jenkins",
"price": 110
},
{
"duration": 45,
"name": "Pipeline",
"price": 110
}
]
},
{
"name": "Advance",
"skills": [
{
"duration": 45,
"name": "Page Object Model",
"price": 120
},
{
"duration": 45,
"name": "Advanced Methods",
"price": 120
},
{
"duration": 45,
"name": "Advanced Logic",
"price": 120
},
{
"duration": 45,
"name": "Your Own Framework",
"price": 120
}
]
},
{
"name": "Professional",
"skills": [
{
"duration": 45,
"name": "Serenit Framework p1",
"price": 130
},
{
"duration": 45,
"name": "Serenit Framework p2",
"price": 130
},
{
"duration": 45,
"name": "Serenit Framework p3",
"price": 130
},
{
"duration": 45,
"name": "Serenit Framework p4",
"price": 130
}
]
}
],
"passion": "Tester",
"s3key": "java.png",
}
]
Deep merge objects/arrays:
Taken from drupal - drupal_array_merge_deep_array and re-written in JS)
function array_merge_deep_array(arrays) {
let result = [];
for (let i in arrays){
for (let key in arrays[i]){
const value = arrays[i][key];
// Renumber integer keys
if (typeof(key) === 'number') {
result.push(value);
}
else if (result[key] && typeof(result[key]) === 'object' && typeof(value) === 'object') {
result[key] = array_merge_deep_array([
result[key],
value,
]);
}
else {
result[key] = value;
}
}
}
return result;
}

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))

Create Object Array in foreach 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']
}
]
}
]
}
});

Categories

Resources