i have the following JavaScript
{
"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": []
}
]
}
]
}
What i am trying to accomplish is when the order comes through a function scans the JSON and creates an array with each unique product name and adds 1 to the quantity each time.
i have tried using a for loop but it loops it the amount of times but doesn't find the name and value in the nested object of each one, it comes back as name = 0 and the value being the individual nested object inside the main object.
A function like the beneath would work. Basically you pass the array as parameter and return an object that 1) gets a new property if the property does not exist yet (eg. the product id), and 2) adds to the count of items when the property does exist. The function below generates an output like: {'product 1': 10, 'product 2': 1, 'product 3': 2}
function getItems(input) {
var arr = input, obj = {};
for (var i = 0; i < arr.length; i++) {
if (!obj[arr[i].name]) {
obj[arr[i].name] = 1;
} else if (obj[arr[i].name]) {
obj[arr[i].name] += 1;
}
}
return obj;
}
// example use
console.log(getItems(order_contents)); // outputs entire object
console.log(getItems(order_contents)['product 1']); // outputs 10
Seeing that you need unique names for each product... you can push the objects into a grouped array of objects then reduce the objects into single unique objects.
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":[]}]}]};
function buildData() {
var items = data.business[0].order_contents, elems = [], groups = [];
for( var i = 0; i < items.length; i++ ) {
Array.prototype.push.call( elems, items[i] );
}
groups.push( groupBy( elems, function( item ) {
return item;
} ) );
groupBy( groups, function( array ) {
for( var i = 0; i < array.length; i++ ) {
var obj = array[i].slice();
Object.keys( obj ).map( function( p ) {
var length = obj.length;
if( obj[p].hasOwnProperty( "quantity" ) ) {
obj[p].quantity = length;
}
groups[i] = obj[p];
} );
}
} );
function groupBy( array, f ) {
var groups = {};
array.forEach( function( o ) {
var group = JSON.stringify( f( o ) );
groups[group] = groups[group] || [];
groups[group].push( o );
} );
return Object.keys( groups ).map( function( group ) {
return groups[group];
} );
}
return groups;
}
(function() {
var old = console.log;
var logger = document.getElementById( 'log' );
console.log = function( message ) {
if( typeof message == 'object' ) {
logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify( message, undefined, 2 ) : message) + '<br />';
} else {
logger.innerHTML += message + '<br />';
}
}
})();
console.log( buildData() );
<pre id="log">
</pre>
Not a big fan of reinventing the wheel, so here is how you could use object-scan to answer your question
// const objectScan = require('object-scan');
const counts = (haystack) => objectScan(['business[*].order_contents[*].name'], {
filterFn: ({ value, context }) => {
context[value] = (context[value] || 0) + 1;
}
})(haystack, {});
const 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: [] }] }]};
console.log(counts(data));
// => { 'product 2': 2, 'product 1': 10, 'product 3': 1 }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.7.1"></script>
Disclaimer: I'm the author of object-scan
Related
i have following example array(object):
[
{
"id": 1,
"name": "selling",
"detail": [
{
"id": 11,
"name": "sale-report",
"detail": [
{ "id": 111, "name": "sale-report1", "detail": [] },
{ "id": 112, "name": "sale-report2", "detail": [] }
]
}
]
},
{
"id": 2,
"name": "webstore",
"detail": [
{
"id": 11,
"name": "sale-report",
"detail": [
{ "id": 111, "name": "webstore-report1", "detail": [] },
{ "id": 112, "name": "webstore-report2", "detail": [] }
]
}
]
},
{
"id": 2,
"name": "setting",
"detail": [
{
"id": 11,
"name": "general",
"detail": [
{ "id": 111, "name": "setting-general1", "detail": [] },
{ "id": 112, "name": "setting-general2", "detail": [] }
]
}
]
}
]
how to change the array with new format like this
[
{
"id": 1,
"name": "selling",
},
{
"id": 11,
"name": "sale-report"
},
{ "id": 111, "name": "sale-report1" },
{ "id": 112, "name": "sale-report2" },
{
"id": 2,
"name": "webstore",
},
{
"id": 11,
"name": "sale-report",
},
{ "id": 111, "name": "webstore-report1" },
{ "id": 112, "name": "webstore-report2" },
{
"id": 2,
"name": "setting",
},
{
"id": 11,
"name": "general",
},
{ "id": 111, "name": "setting-general1" },
{ "id": 112, "name": "setting-general2" }
]
with the condition that if there is a key "detail" inside object in the branch, it will be mapped as well (assuming unlimited key "detail" inside object inside array)
note: content of detail will be same as parent, but different value
thanks in advance
i tried mapping mannualy with foreach, but i cant figure out if detail key with array(object) has unlimited nesting
Simply, use recursion to do this.
Here is the working demo-
let input = [
{
id: 1,
name: "selling",
detail: [
{
id: 11,
name: "sale-report",
detail: [
{ id: 111, name: "sale-report1", detail: [] },
{ id: 112, name: "sale-report2", detail: [] }
]
}
]
},
{
id: 2,
name: "webstore",
detail: [
{
id: 11,
name: "sale-report",
detail: [
{ id: 111, name: "webstore-report1", detail: [] },
{ id: 112, name: "webstore-report2", detail: [] }
]
}
]
},
{
id: 2,
name: "setting",
detail: [
{
id: 11,
name: "general",
detail: [
{ id: 111, name: "setting-general1", detail: [] },
{ id: 112, name: "setting-general2", detail: [] }
]
}
]
}
];
let result = [];
function parseData(arr) {
arr.forEach((item) => {
result.push({
id: item.id || null,
name: item.name || null
});
if (item.detail && item.detail.length) {
parseData(item.detail);
}
});
return result;
}
let output = parseData(input);
console.log(output);
You could destructure the objects and take detail out of the object and map the rest object and the results of nested details array as flat array with a recursive function.
const
flat = (array = []) => array.flatMap(({ detail, ...rest }) => [
rest,
...flat(detail)
]),
data = [{ id: 1, name: "selling", detail: [{ id: 11, name: "sale-report", detail: [{ id: 111, name: "sale-report1", detail: [] }, { id: 112, name: "sale-report2", detail: [] }] }] }, { id: 2, name: "webstore", detail: [{ id: 11, name: "sale-report", detail: [{ id: 111, name: "webstore-report1", detail: [] }, { id: 112, name: "webstore-report2", detail: [] }] }] }, { id: 2, name: "setting", detail: [{ id: 11, name: "general", detail: [{ id: 111, name: "setting-general1", detail: [] }, { id: 112, name: "setting-general2", detail: [] }] }] }],
result = flat(data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
A non recursive method of doing this could look something like the following:
const data = [{"id":1,"name":"selling","detail":[{"id":11,"name":"sale-report","detail":[{"id":111,"name":"sale-report1","detail":[]},{"id":112,"name":"sale-report2","detail":[]}]}]},{"id":2,"name":"webstore","detail":[{"id":11,"name":"sale-report","detail":[{"id":111,"name":"webstore-report1","detail":[]},{"id":112,"name":"webstore-report2","detail":[]}]}]},{"id":2,"name":"setting","detail":[{"id":11,"name":"general","detail":[{"id":111,"name":"setting-general1","detail":[]},{"id":112,"name":"setting-general2","detail":[]}]}]}];
const extract = (data) => {
const result = [];
const queue = [...data];
while(queue.length > 0) {
const { detail, ...rest } = queue.shift();
result.push(rest);
queue.unshift(...detail);
}
return result;
};
console.log(extract(data));
I have two array of objects that are linked by a parent ID. I am trying to make a list of categories, and in each category is a set of data that corresponds to its respective category. It will be a header (category), then a set of buttons (data). The header data has an ID, the button data has a parentId based on the headers regular ID
ex. Category 1 ID = 62, Button 3 parent ID = 62.
I need to create a way to display each category with its respective data.
Category array:
[
{
"categoryName":"Category 1",
"id":62,
"parentId":0,
"txt":"category1"
},
{
"categoryName":"Category 2",
"id":60,
"parentId":0,
"txt":"category2"
},
{
"categoryName":"Category 3",
"id":61,
"parentId":0,
"txt":"category3"
},
{
"categoryName":"Category 4",
"id":59,
"parentId":0,
"txt":"category4"
}
]
Data array:
[
{
"categoryName":"Button 1",
"id":29,
"isChecked":false,
"parentId":60,
"txt":"button1"
},
{
"categoryName":"Button 2",
"id":31,
"isChecked":false,
"parentId":61,
"txt":"button2"
},
{
"categoryName":"Button 3",
"id":35,
"isChecked":false,
"parentId":62,
"txt":"button3"
},
{
"categoryName":"Button 4",
"id":37,
"isChecked":false,
"parentId":62,
"txt":"button4"
},
{
"categoryName":"Button 5",
"id":39,
"isChecked":false,
"parentId":59,
"txt":"button5"
},
{
"categoryName":"Button 6",
"id":41,
"isChecked":false,
"parentId":59,
"txt":"button6"
}
]
Looking for something like this??:
[
{
categoryName: 'Category 1',
id: 62,
parentId: 0,
txt: 'category1',
children: [
{
categoryName: 'Category 1',
id: 62,
parentId: 0,
txt: 'category1',
},
],
},
{
categoryName: 'Category 2',
id: 60,
parentId: 0,
txt: 'category2',
},
{
categoryName: 'Category 3',
id: 61,
parentId: 0,
txt: 'category3',
},
{
categoryName: 'Category 4',
id: 59,
parentId: 0,
txt: 'category4',
},
]
// categories is your top level categories object and data is the children you posted
const tree = categories.map(category => {
return {
...category,
children: data.filter(child => child.parentId === category.id)
}
})
What we do here is first loop over the top level categories. We then return the category untouched, but merged with the children property, which is set to the items in the second dataset which have a matching parentId to the top level category currently being processed in that first loop.
The expected result your provided isn't consistent. But I think I can work with that.
var arr_cat = [{
"categoryName": "Category 1",
"id": 62,
"parentId": 0,
"txt": "category1"
}, {
"categoryName": "Category 2",
"id": 60,
"parentId": 0,
"txt": "category2"
}, {
"categoryName": "Category 3",
"id": 61,
"parentId": 0,
"txt": "category3"
},
{
"categoryName": "Category 4",
"id": 59,
"parentId": 0,
"txt": "category4"
}
];
var arr_data = [{
"categoryName": "Button 1",
"id": 29,
"isChecked": false,
"parentId": 60,
"txt": "button1"
},
{
"categoryName": "Button 2",
"id": 31,
"isChecked": false,
"parentId": 61,
"txt": "button2"
},
{
"categoryName": "Button 3",
"id": 35,
"isChecked": false,
"parentId": 62,
"txt": "button3"
},
{
"categoryName": "Button 4",
"id": 37,
"isChecked": false,
"parentId": 62,
"txt": "button4"
},
{
"categoryName": "Button 5",
"id": 39,
"isChecked": false,
"parentId": 59,
"txt": "button5"
},
{
"categoryName": "Button 6",
"id": 41,
"isChecked": false,
"parentId": 59,
"txt": "button6"
}
]
// first group categories by their id's for easy access.
var obj = arr_cat.reduce(function(agg, item) {
agg[item.id] = item;
return agg;
}, {});
// then assign each data to the relevant sub-object
arr_data.forEach(function(item) {
if (obj[item.parentId]) {
obj[item.parentId].children = obj[item.parentId].children || []
obj[item.parentId].children.push(item);
}
});
// finally get the values array
var final = Object.values(obj);
console.log(final);
.as-console-wrapper {
max-height: 100% !important;
}
how can i convert returned data from this structure:
[
{
"id": 91,
"name": "Art",
"division": {
"id": 4,
"name": "1st level",
"created_at": "2018-11-05T10:11:37+00:00",
},
"created_at": "2018-11-05T10:11:37+00:00",
},
{
"id": 188,
"name": "English",
"division": {
"id": 9,
"name": "3rd level",
"created_at": "2018-11-05T10:11:37+00:00",
},
"created_at": "2018-11-05T10:11:37+00:00",
},
{
"id": 218,
"name": "Art",
"division": {
"id": 11,
"name": "3rd level",
"created_at": "2018-11-05T10:11:37+00:00",
},
"created_at": "2018-11-05T10:11:37+00:00",
}
]
to this structure :
[
{
"id": 1,
"name": "Art",
"classes": [
{
"id": 91,
"name": "1st level",
},
{
"id": 218,
"name": "3rd level",
},
],
},
{
"id": 2,
"name": "English",
"classes": [
{
"id": 188,
"name": "3rd level",
},
],
},
]
note: class.id = parentSubject.id
I wrote some codes to solve the problem but I'm looking for the best way !!
i use .reduce() function
I will attach the codes in the comments box.
Here is how I would do it:
let ans = initialArray.reduce((cum,x) => {
let foundIndex = cum.findIndex((a) =>{
return a.name == x.name});
if(foundIndex!=-1){
cum[foundIndex].classes.push({
id : x.id,
name : x.division.name
})
}
else{
cum.push({
id : cum.length+1,
name : x.name,
classes : [{
id : x.id,
name : x.division.name
}]
})
}
return cum;
},[]);
I use reduce and findIndex methods.
You can use array map to create a new array of objects with the new id.
const oldDatas = [
{
id: 91,
name: 'Art',
division: {
id: 4,
name: '1st level',
created_at: '2018-11-05T10:11:37+00:00',
},
created_at: '2018-11-05T10:11:37+00:00',
},
{
id: 188,
name: 'English',
division: {
id: 9,
name: '3rd level',
created_at: '2018-11-05T10:11:37+00:00',
},
created_at: '2018-11-05T10:11:37+00:00',
},
{
id: 218,
name: 'Art',
division: {
id: 11,
name: '3rd level',
created_at: '2018-11-05T10:11:37+00:00',
},
created_at: '2018-11-05T10:11:37+00:00',
},
];
const newDatas = oldDatas.map((data, index) => {
return { ...data, id: index + 1 };
});
console.log(newDatas);
my solution :
let res = initialArray.reduce((acc, obj) => {
const exist = acc.findIndex((item) => item.name === obj.name);
if (exist >= 0) {
acc[exist] = {
id: exist,
name: obj.name,
classes: [
...acc[exist].classes,
{ id: obj.id, name: obj.division.name },
],
};
} else {
acc.push({
id: acc.length,
name: obj.name,
classes: [{ id: obj.id, name: obj.division.name }],
});
}
return acc;
}, []);
This is my array
"status": "Success",
"results": 54,
"orders": [
{
"order_id": 261,
"image": "test1.png",
"productName": "test1",
"price": 2,
"quantity": 2,
"purAmt": 34,
"created_at": "2020-07-27T06:29:32.000Z",
"shopName": "abc"
},
{
"order_id": 261,
"image": "test2.png",
"productName": "test2",
"price": 30,
"quantity": 1,
"purAmt": 34,
"created_at": "2020-07-27T06:29:32.000Z",
"shopName": "abc"
},
]
I want to combine properties with same name and create array of object within a object.
expected output
"status": "Success",
"results": 54,
"orders": [
{
"order_id": 261,
"purAmt": 34,
"created_at": "2020-07-27T06:29:32.000Z",
"shopName": "abc"
products : [
{
"productName": "test1",
"price": 2,
"quantity": 2,
"image": "test1.png",
},
{
"productName": "test2",
"price": 5,
"quantity": 3,
"image": "test2.png",
},
}
]
I would be better if I get the solution using reduce function and without any libraries like lodash
My attempt of doing it using reduce fcn
var result = Object.values(
data.reduce(
(acc, { productName, price, image, quantity, ...rest }) => {
acc[rest.orderID] = acc[rest.orderID] || { ...rest, products: [] };
acc[rest.orderID].products.push({
productName,
price,
image,
quantity,
});
return acc;
},
{},
),
);
This should work for you
orders = [
{
order_id: 261,
image: "test1.png",
productName: "test1",
price: 2,
quantity: 2,
purAmt: 34,
created_at: "2020-07-27T06:29:32.000Z",
shopName: "abc",
},
{
order_id: 261,
image: "test2.png",
productName: "test2",
price: 30,
quantity: 1,
purAmt: 34,
created_at: "2020-07-27T06:29:32.000Z",
shopName: "abc",
},
];
const res = Object.values(
orders.reduce((acc, { image, productName, price, quantity, ...rest }) => {
if (!acc[rest.order_id]) {
acc[rest.order_id] = { products: [] };
}
acc[rest.order_id] = {
...acc[rest.order_id],
...rest,
products: [
...acc[rest.order_id].products,
{
image,
productName,
price,
quantity,
},
],
};
return acc;
}, {})
);
console.log(res);
Extended Version: I extend it, so there are now different order_id's considered. For example I add a id 262 which creates another element in orders-array.
let data = { "status": "Success",
"results": 54,
"orders": [
{
"order_id": 261,
"image": "test1.png",
"productName": "test1",
"price": 2,
"quantity": 2,
"purAmt": 34,
"created_at": "2020-07-27T06:29:32.000Z",
"shopName": "abc"
},
{
"order_id": 262,
"image": "test3.png",
"productName": "test3",
"price": 70,
"quantity": 5,
"purAmt": 17,
"created_at": "2020-07-19T06:29:32.000Z",
"shopName": "xyz"
},
{
"order_id": 261,
"image": "test2.png",
"productName": "test2",
"price": 30,
"quantity": 1,
"purAmt": 34,
"created_at": "2020-07-27T06:29:32.000Z",
"shopName": "abc"
},
]};
let orderIndex =[];
let orders = [];
data.orders.forEach(orderObj => {
let order;
let index = orderIndex.indexOf(orderObj.order_id);
if (index == -1) {
orderIndex.push(orderObj.order_id);
order = {};
orders.push(order);
['order_id', 'purAmt', 'created_at', 'shopName'].forEach( elem => {
order[elem] = orderObj[elem];
order.products = [];
});
} else {
order = orders[index];
}
let product = {};
['productName', 'price', 'image', 'quantity'].forEach( elem => {
product[elem] = orderObj[elem];
});
order.products.push(product);
});
let result = {
status: data.status,
results: data.results,
orders: orders
}
console.log(result);
I have the following JSON array:
[
{ id: 1, name: "P1", groups: [ { id: 1.1, name: "G1.1" }, { id: 1.2, name:"G1.2" }]},
{ id: 2, name: "P2", groups: [ { id: 2.1, name: "G2.1" }, { id: 2.2, name:"G2.2" }]}
];
What is the most efficient method to convert it to the following structure using Javascript ES6?
[
{ id: 1, name: "P1", group_id: 1.1, group_name: "G1.1"},
{ id: 1, name: "P1", group_id: 1.2, group_name: "G1.2"},
{ id: 2, name: "P2", group_id: 1.1, group_name: "G2.1"},
{ id: 2, name: "P2", group_id: 1.1, group_name: "G2.2"},
]
There are some problems.
If it is a json array, it should be like this.
var obj = [{
"id": 1,
"name": "P1",
"groups": [{
"id": 1.1,
"name": "G1.1"
}, {
"id": 1.2,
"name": "G1.2"
}]
},
{
"id": 2,
"name": "P2",
"groups": [{
"id": 2.1,
"name": "G2.1"
}, {
"id": 2.2,
"name": "G2.2"
}]
}
];
you can validate json arrays using this link
it little bit confused about your out put.That's why it made voting down.
After set an array, you can use ForEach for that.
var obj = [{
"id": 1,
"name": "P1",
"groups": [{
"id": 1.1,
"name": "G1.1"
}, {
"id": 1.2,
"name": "G1.2"
}]
},
{
"id": 2,
"name": "P2",
"groups": [{
"id": 2.1,
"name": "G2.1"
}, {
"id": 2.2,
"name": "G2.2"
}]
}
];
res = [];
obj.forEach((e)=>{
e.groups.forEach((group)=>{
res.push({
"id" : e.id,
"name" : e.name,
"group_id" : group.id,
"group_name" : group.name
});
});
});
console.log(res);
You can achieve this using forEach.
Try the following:
var arr=[
{ id: 1, name: "P1", groups: [ { id: 1.1, name: "G1.1" }, { id: 1.2, name:"G1.2" }]},
{ id: 2, name: "P2", groups: [ { id: 2.1, name: "G2.1" }, { id: 2.2, name:"G2.2" }]}
];
result = [];
arr.forEach((o)=>{
o.groups.forEach((group)=>{
result.push({
"id" : o.id,
"name" : o.name,
"group_id" : group.id,
"group_name" : group.name
});
});
});
console.log(result);