Getting Value (Description) of an object's property in another object - javascript

I have to array of objects which can be related to each other through CategoryId. like below code:
const Category = [
{ ID: 100 , Description: Cate1},
{ID: 101 , Description: Cate2}
]
const Items = [
{ID: 2001, CategoryID: 100, Desc: Item1 },
{ID: 2002, CategoryID: 100, Desc: Item2 },
{ID: 2003, CategoryID: 101, Desc: Item3 },
]
I am going to distribute items by the use of map method in lis that are summarized in their own ul according to the category descriptions that are extracted from category id which exists in both arrays. For example:
Cate1 > ul
item1 > li
item2 > li
Cate2 > ul
item3 > li
.
.
.
How can I tackle this issue with Javascript or ES6/7/8?

You can look at each category and for each one filter() the matching items. This is easy, but will be a little slow if you have lots of data because you loop though the item list every time:
const Category = [{ ID: 100 , Description: 'Cate1'}, {ID: 101 , Description: 'Cate2'}]
const Items = [ {ID: 2001, 'CategoryID': 100, Desc: 'Item1' }, {ID: 2002, 'CategoryID': 100, Desc: 'Item2' }, {ID: 2003, 'CategoryID': 101, Desc: 'Item3' }, ]
Category.forEach(cat => {
console.log('ul> '+cat.Description)
Items.filter(item => item.CategoryID === cat.ID)
.forEach(item => console.log(' li> ' + item.Desc))
})
Alternatively you can build a lookup table for your items base on ID once, and then use it to find the items in constant time. This will be faster with larger data, but requires a little more work upfront:
const Category = [{ ID: 100 , Description: 'Cate1'}, {ID: 101 , Description: 'Cate2'}]
const Items = [ {ID: 2001, 'CategoryID': 100, Desc: 'Item1' }, {ID: 2002, 'CategoryID': 100, Desc: 'Item2' }, {ID: 2003, 'CategoryID': 101, Desc: 'Item3' }, ]
let lookup = Items.reduce((a, c) => {
(a[c.CategoryID] || (a[c.CategoryID] = [])).push(c)
return a
}, {})
Category.forEach(cat => {
console.log('ul> '+cat.Description)
lookup[cat.ID]
.forEach(item => console.log(' li> ' + item.Desc))
})

Related

Javascript Algorithm for inventory

I have a problem, which I solved already but I feel like my implementation is very basic and could definitely learn a better way to do this.
Given 2 array of objects, one for the sales that my customers are demanding, and one for the purchases that I'm doing to my provider, I need to be able to place the orders and know when I will be able to satisfy them. I will only work with one product, to make it simpler.
I'm very new at coding this case of problems, so I would really apreciate a point in the right direction. Maybe there's a data structure that I haven't used that could help here.
Properties:
'created': when the sales order was created
'quantity': how many items the customer wants
const sales= [{
'id': 'S1',
'created': '2020-01-02',
'quantity': 6
}, {
'id': 'S2',
'created': '2020-11-05',
'quantity': 2
}, {
'id': 'S3',
'created': '2019-12-04',
'quantity': 3
}, {
'id': 'S4',
'created': '2020-01-20',
'quantity': 2
}, {
'id': 'S5',
'created': '2019-12-15',
'quantity': 9
}];
Properties:
'receiving': when we expect to receive the product
'quantity': how many we will be receiving
const purchases= [{
'id': 'P1',
'receiving': '2020-01-04',
'quantity': 4
}, {
'id': 'P2',
'receiving': '2020-01-05',
'quantity': 3
}, {
'id': 'P3',
'receiving': '2020-02-01',
'quantity': 5
}, {
'id': 'P4',
'receiving': '2020-03-05',
'quantity': 1
}, {
'id': 'P5',
'receiving': '2020-02-20',
'quantity': 7
}];
My code so far. I'm returnign an array that for reach sales, it shows when I will be able to satisfy it. The problem that I'm running with the current implementation is that I cannot cover all the cases.
function allocate(salesOrders, purchaseOrders) {
//ordering sales and purchases by date
const orderedSales = salesOrders.sort((a, b) => a.created.localeCompare(b.created));
const orderedPurchases = purchaseOrders.sort((a, b) => a.receiving.localeCompare(b.receiving));
console.log(orderedSales)
console.log(orderedPurchases)
let stock = 0;
const result = [];
purchaseIndex = 0;
orderedSales.forEach((sale, index) => {
const order = orderedPurchases[purchaseIndex];
if (order) {
console.log("Processing order", sale.id)
console.log(`Leftover stock = ${stock}`)
stock += order.quantity
console.log(`new stock = ${stock}`)
stock = stock - sale.quantity;
console.log(`Sustracting = ${sale.quantity}`)
console.log(`Remaining = ${stock}`)
while (stock < 0) {
purchaseIndex++
console.log(`Demand NOT satified, moving to next purchase order with index ${purchaseIndex}`)
stock += order.quantity
console.log(`Current stock = ${stock}`)
increaseOrder = false;
}
//demand has been satisfied
console.log(`Demand for ${sale.id} was satified with purchase ${order.id}, time is ${order.receiving}, moving to next purchase order`)
result.push({
id: sale.id,
availabilityDate: order.receiving
})
purchaseIndex++
console.log("Next sale ++++++++")
console.log(" ++++++++")
}
});
console.log(result);
}
allocate(salesOrders, purchaseOrders)
I think your approach is mostly ok. I would just have some remarks/questions:
is it ok to always have stock start at 0? They are never left over? According to me, it should be one of the parameters of the allocate function
you should handle the case where the purchases are not enough to satisfy the sales (which is the case in your example data set) => with your current code your while loop could go over the max allowed index of the purchases array and throw an exception
if a sale can be satisfied before its creation date, should the availability date be before the creation date or should it be forced to the creation date? (if sales are always in the past and purchases in the future, this question doesn't make sense)
Here is how I would tackle the problem:
console.log(allocate(salesOrders, purchaseOrders));
function allocate(_sales, _purchases) {
const sales = structureData(_sales, "created");
const purchases = structureData(_purchases, "receiving");
const LAST_PURCHASE_INDEX = purchases.length - 1;
let stock = 0; // in real life, maybe this should be an input as well since it might not always start from 0?
let availabilityDate = sales[0].date; // timestamp of stock availability, initialized to first sale timestamp
let availabilityDateString = sales[0].created; // date in string format of stock availability, initialized to first sale created date
let purchaseIndex = 0; // index of the next purchase to process
const result = [];
// loop on sales
for (let sale of sales) {
const requiredQuantity = sale.quantity;
const saleId = sale.id;
// As long as we don't have enough stock, process the next purchase if there is any
while (stock < requiredQuantity && purchaseIndex <= LAST_PURCHASE_INDEX) {
const purchase = purchases[purchaseIndex];
stock += purchase.quantity;
availabilityDate = purchase.date;
availabilityDateString = purchase.receiving;
purchaseIndex++;
}
if (stock >= requiredQuantity) { // we have enough stock and push the availability date
result.push({
id: saleId,
availabilityDate:
availabilityDate > sale.date ? availabilityDateString : sale.created, // It could be simplified to availabilityDate if it's ok to have an availabilityDate before the sales creation
});
stock -= sale.quantity;
} else { // we don't have enough stock and there are no purchases left, so we need more purchases
result.push({ id: saleId , availabilityDateString: "Not anytime soon, need more purchases"});
}
}
return result;
}
// utils to sort orders and add a date timesteamp for easier date comparison
function structureData(orders, dateField) {
return orders
.map((order) => ({ ...order, date: new Date(order[dateField]).getTime() }))
.sort((o1, o2) => o1.date - o2.date);
}
I would do it like this. First I would create a collection of events that have type, date, id, and quantity fields, then sort them by date. This intermediate format might look like this:
[
{type: "sale", date: "2019-12-04", id: "S3", quantity: 3},
{type: "sale", date: "2019-12-15", id: "S5", quantity: 9},
{type: "sale", date: "2020-01-02", id: "S1", quantity: 6},
{type: "purchase", date: "2020-01-04", id: "P1", quantity: 4},
{type: "purchase", date: "2020-01-05", id: "P2", quantity: 3},
{type: "sale", date: "2020-01-20", id: "S4", quantity: 2},
{type: "purchase", date: "2020-02-01", id: "P3", quantity: 5},
{type: "purchase", date: "2020-02-20", id: "P5", quantity: 7},
{type: "purchase", date: "2020-03-05", id: "P4", quantity: 1},
{type: "sale", date: "2020-11-05", id: "S2", quantity: 2}
]
Then I would fold this list of events into a structure with onHand, completed and open properties by checking each event. If it's a purchase, then we add its quantity to onHand. Then we loop through the existing open events (plus the current one if it's a sale), creating new entries to add to the existing completed array if the quantity is not bigger than onHand, and adding to a new open array if it's too large. The code could look like this:
const process = (initial) => (sales, purchases) => [
...sales.map (({created, ...rest}) => ({type: 'sale', date: created, ...rest})),
...purchases.map (({receiving, ...rest}) => ({type: 'purchase', date: receiving, ...rest})),
] .sort (({date: d1}, {date: d2}) => d1 < d2 ? -1 : d1 > d2 ? 1 : 0) .reduce ((
{onHand, open: o, completed},
{type, date, quantity, id, open = [...o, ... (type == 'sale' ? [{quantity, date, id}] : [])]}
) => open .reduce (
({onHand, open, completed}, {quantity, date: saleDate, id}) => quantity <= onHand
? {onHand: onHand - quantity, open, completed: completed .concat ({date, id, quantity})}
: {onHand, open: open .concat ({quantity, date: saleDate, id}), completed},
{onHand: onHand + (type == 'purchase' ? quantity : 0) , open: [], completed}
), initial)
const allocate = process ({onHand: 0, open: [], completed: []})
const salesOrders = [{id: "S1", created: "2020-01-02", quantity: 6}, {id: "S2", created: "2020-11-05", quantity: 2}, {id: "S3", created: "2019-12-04", quantity: 3}, {id: "S4", created: "2020-01-20", quantity: 2}, {id: "S5", created: "2019-12-15", quantity: 9}]
const purchaseOrders = [{id: "P1", receiving: "2020-01-04", quantity: 4}, {id: "P2", receiving: "2020-01-05", quantity: 3}, {id: "P3", receiving: "2020-02-01", quantity: 5}, {id: "P4", receiving: "2020-03-05", quantity: 1}, {id: "P5", receiving: "2020-02-20", quantity: 7}]
console .log (allocate (salesOrders, purchaseOrders))
.as-console-wrapper {max-height: 100% !important; top: 0}
This structure we folded to serves as our overall output, something like this:
{
onHand: 0,
completed: [
{date: "2020-01-04", id: "S3", quantity: 3},
{date: "2020-01-20", id: "S4", quantity: 2},
{date: "2020-02-01", id: "S1", quantity: 6},
{date: "2020-03-05", id: "S5", quantity: 9}
],
open: [
{date: "2020-11-05", id: "S2", quantity: 2}
]
}
But that suggests an improvement. We could make this function reentrant. We could save the output, then next time we need to add events, we could simply pass that back through the function with new sales and purchases. This would give you an updated list. It seems like a handy feature, and it's not any more difficult to add. The only real API change is that you now pass the current value in every call, with some default values for the initial call. Here is one version:
const process = (initial, sales, purchases) => [
...sales.map (({created, ...rest}) => ({type: 'sale', date: created, ...rest})),
...purchases.map (({receiving, ...rest}) => ({type: 'purchase', date: receiving, ...rest})),
] .sort (({date: d1}, {date: d2}) => d1 < d2 ? -1 : d1 > d2 ? 1 : 0) .reduce ((
{onHand, open: o, completed},
{type, date, quantity, id, open = [...o, ... (type == 'sale' ? [{quantity, date, id}] : [])]}
) => open .reduce (
({onHand, open, completed}, {quantity, date: saleDate, id}) => quantity <= onHand
? {onHand: onHand - quantity, open, completed: completed .concat ({date, id, quantity})}
: {onHand, open: open .concat ({date: saleDate, id, quantity}), completed},
{onHand: onHand + (type == 'purchase' ? quantity : 0) , open: [], completed}
), initial)
const salesOrders = [{id: "S1", created: "2020-01-02", quantity: 6}, {id: "S2", created: "2020-11-05", quantity: 2}, {id: "S3", created: "2019-12-04", quantity: 3}, {id: "S4", created: "2020-01-20", quantity: 2}, {id: "S5", created: "2019-12-15", quantity: 9}]
const purchaseOrders = [{id: "P1", receiving: "2020-01-04", quantity: 4}, {id: "P2", receiving: "2020-01-05", quantity: 3}, {id: "P3", receiving: "2020-02-01", quantity: 5}, {id: "P4", receiving: "2020-03-05", quantity: 1}, {id: "P5", receiving: "2020-02-20", quantity: 7}]
const initialValues = {onHand: 0, open: [], completed: []}
const currentState = process (initialValues, salesOrders, purchaseOrders)
console .log ('initial load: ', currentState)
const additionalSalesOrders = [{id: "S6", created: "2021-03-07", quantity: 3}, {id: "S7", created: "2021-04-21", quantity: 10}, {id: "S3", created: "2021-06-14", quantity: 5}]
const additionalPurchaseOrders = [{id: "P6", receiving: "2021-05-20", quantity: 8}]
const nextState = process (currentState, additionalSalesOrders, additionalPurchaseOrders)
console .log ('after new events: ', nextState)
.as-console-wrapper {max-height: 100% !important; top: 0}

How to return a new array of objects that contains merged data from source and target?

I want to compare an oldItems array of objects and if id matches the id in my updatedItems array of objects, I want to update the object, copying over the property from oldItems if there is no value in updatedItems for that key or if that property is not defined, and replacing the oldItems object property with the updatedItems object property if there IS a value. I want to store all the changes in a result variable and log result to the console.
The result variable should contain exactly an object with id: 1, the new sandwich name, and the old price, as well as id: 2 with the new price and the new name.
const oldItems = [
{
id: 0,
name: "peanut butter sandwich",
price: 3
},
{
id: 1,
name: "cheese sandwich",
price: 4
},
{
id: 2,
name: "chicken sandwich",
price: 6
}
]
const updatedItems =
[{
id: 1,
name: "grilled cheese sandwich"
}, {
id: 2,
price: 5,
name: "chicken and waffles sandwich"
}]
I tried:
let result = oldItems.map((item, i) => Object.assign({}, item, updatedItems[i]));
console.log(result);
I'm not completely certain of your use-case, but this will produce the result you describe.
oldItems.map(o => {
const update = updatedItems.find(u => u.id === o.id);
if (update) return {
...o,
...update
}
}).filter(x => x)
result :
[
{ id: 1, name: 'grilled cheese sandwich', price: 4 },
{ id: 2, name: 'chicken and waffles sandwich', price: 5 }
]
First, your code maps over the wrong array, you should be mapping updatedItems.
Second, you can't use the same i for both arrays, since the items with the same id are not at the same indexes. Use find() to search the array for the id.
In ES6 you can use ... to merge objects instead of Object.assign().
const oldItems = [{
id: 0,
name: "peanut butter sandwich",
price: 3
},
{
id: 1,
name: "cheese sandwich",
price: 4
},
{
id: 2,
name: "chicken sandwich",
price: 6
}
];
const updatedItems = [{
id: 1,
name: "grilled cheese sandwich"
}, {
id: 2,
price: 5,
name: "chicken and waffles sandwich"
}];
let result = updatedItems.map((item) => ({
...oldItems.find(el => el.id == item.id),
...item
}));
console.log(result);

How to add property value from one array of objects into another (for the matching objects) in JS

I am trying to filter array of objects based on another array of objects and after finding all matching items I want to set property and value from the first array object into corresponding object in the second array:
const searchedProducts = products.filter(product =>
uniqueProducts.some(
uniqueProduct =>
product.productId === uniqueProduct.productId,
),
)
After here I need to set product.productName for each unique product object under productName property.
Ho such a thing can be achieved in a better way?
This is probably most straightforward using reduce() combined with find() to both retrieve and verify that the second array contains each object.
const uniqueProducts = [
{id: 3, from: 'uniqueProducts', name: 'Unique 1'},
{id: 12, from: 'uniqueProducts', name: 'Unique 12'}
];
const products = [
{id: 1, from: 'products', name: 'Product 1'},
{id: 2, from: 'products', name: 'Product 2'},
{id: 9, from: 'products', name: 'Product 9'},
{id: 12, from: 'products', name: 'Product 12'},
];
const output = products.reduce((a, p) => {
const uP = uniqueProducts.find(u => u.id === p.id);
if (uP) a.push({...p, name: uP.name});
return a;
}, []);
console.log(output);
I have inventory where I have to add a price property and take its value from products array so I did this,
inventory = [
{
"productId": 1,
"quantity": 100,
"name": "2 Yolks Noodles",
"image": "twoeggnoodles.jpg",
}
]
Products = [
{
"id": 1,
"quantity": 100,
"name": "2 Yolks Noodles",
"image": "twoeggnoodles.jpg",
"price": 34.95
}
]
let product:any = [];
products.map((prod:any)=>{
const index:any = inventory.find((u:any) => u.productId === prod.id);
// console.log("item", index, '-', prod)
if(index){
product.push({...index, price: prod.price});
}
return prod
})
});

find an object in Array of Array

if i want for an example loop Through this Array to find specific item in Items Array how to approach that? i made this logic but it doesn't work
DATA.map((D)=>{
return D.items.find((item)=>{
return item.name ==='Blue Beanie'
})
})
this is the Array plus how to create new ONE array includes the both of items arrays to be like that: items: [{
id: 1,
name: 'Brown Brim',
price: 25
},
{
id: 2,
name: 'Blue Beanie',
price: 18
},
{
id: 3,
name: 'Adidas NMD',
price: 220
},
{
id: 4,
name: 'Adidas Yeezy',
price: 280
}
]
const DATA= [
{
id: 1,
title: 'Hats',
routeName: 'hats',
items: [
{
id: 1,
name: 'Brown Brim',
price: 25
},
{
id: 2,
name: 'Blue Beanie',
price: 18
}
]
},
{
id: 2,
title: 'Sneakers',
routeName: 'sneakers',
items: [
{
id: 3,
name: 'Adidas NMD',
price: 220
},
{
id: 4,
name: 'Adidas Yeezy',
price: 280
}
]
}
];
Transform DATA into list of items and find from that list your expected item
const res = DATA.flatMap((D) => D.items).find(
(item) => item.name === "Brown Brim"
)
const DATA = [
{
id: 1,
title: "Hats",
routeName: "hats",
items: [
{
id: 1,
name: "Brown Brim",
price: 25,
},
{
id: 2,
name: "Blue Beanie",
price: 18,
},
],
},
{
id: 2,
title: "Sneakers",
routeName: "sneakers",
items: [
{
id: 3,
name: "Adidas NMD",
price: 220,
},
{
id: 4,
name: "Adidas Yeezy",
price: 280,
},
],
},
]
const res = DATA.flatMap((D) => D.items).find(
(item) => item.name === "Brown Brim"
)
console.log(res)
Reference
Array.prototype.flatMap()
Maybe this is helpful?
const DATA= [
{id: 1,title:'Hats',routeName:'hats',
items:[{id: 1,name:"Brown Brim",price:25},
{id: 2,name: 'Blue Beanie',price: 18}]},
{id: 2,title: 'Sneakers',routeName: 'sneakers',
items: [{id: 3,name: 'Adidas NMD',price: 220},
{id: 4,name: 'Adidas Yeezy',price: 280}]}
];
console.log(DATA.map(D=>D.items.find(item=>item.name==='Brown Brim'))
.filter(e=>e))
The .map returns either an element matching your criterion or undefined, The chained .filter then removes all "falsy" elements, i. e. all the undefined ones.
As for the first question "loop Through this Array to find a specific item in Items Array"
given it is not sorted in any way, this can be done by iterating over the DATA array and search inside the items
If want to have access to the item from the outside of the 'forEach' scope you have to declare the variable outside
Regarding the second question, use the reduce function while iterating the array
NOTE: You can obviously combine both tasks as you already iterate through the array, so no need to do it twice. But to avoid confusion, I separated the logic.
Also, if you do choose to combine the tasks, using the reduce is not relevant, but very much like the answer to the first question, you can declare a buffer such as an array, and just copy items to it on the go (I'll leave out questions on performance for that matter)
const DATA = [
{
id: 1, title: 'Hats', routeName: 'hats',
items: [
{id: 1,name: 'Brown Brim',price: 25},
{id: 2,name: 'Blue Beanie',price: 18}
]
},
{
id: 2, title: 'Sneakers', routeName: 'sneakers',
items: [
{id: 3,name: 'Adidas NMD',price: 220},
{id: 4,name: 'Adidas Yeezy',price: 280}
]
}
];
//Question 1
//creating the object that will hold the item
//outside of the 'forEach' scope so we can use it later
let res = {};
const searchRes = DATA.forEach(entry => {
entry.items.forEach(item => {
if (item.name === 'Brown Brim')
//duplicating the item to a variable declared outside of this scope
res = { ...item
};
});
});
console.log(`Q1 - The item we found:`);
console.log(res);
// Question 2
// Merging all object inside the 'items' array using Reduce
const merged = DATA.reduce((acc, curr) =>
acc.concat(curr.items), []);
console.log(`Q2 - The merged array:`);
console.log(merged)

How to groupBy an object key inside nested array of objects?

I have a nested array of objects and I want to groupBy id and form a new array. Here's my array:
mainArray = [
{ name: 'a',age: 10, company: [ { desc: 'test1' , id: 6 }, { desc: 'testa' , id: 10 }] },
{ name: 'b',age: 20, company: [ { desc: 'test2' , id: 30 }] },
{ name: 'c',age: 40, company: [ { desc: 'test3' , id: 10 }, { desc: 'testc' , id: 30 }] }
]
I can flatten the entire array but it doesn't seem like the right way to do it.
My new array should look like something like this:
result = [
comapny_6: [
{
name: 'a',
age: 10,
desc: 'test1'
},
],
comapny_10: [
{
name: 'a',
age: 10,
desc: 'testa'
},
{
name: 'c',
age: 40,
desc: 'test3'
}
],
company_30 :[
{
name: 'b',
age: 20,
desc: 'test2'
},
{
name: 'c',
age: 40,
desc: 'testc'
}
]
]
I am open to suggestions on how the final data structure should look like. The bottom line is I want groupBy id so that I have information about each company separated out.
You can use reduce to loop thru the array and construct the desired object output. Use forEach to loop thru company
var mainArray = [{"name":"a","age":10,"company":[{"desc":"test1","id":6},{"desc":"testa","id":10}]},{"name":"b","age":20,"company":[{"desc":"test2","id":30}]},{"name":"c","age":40,"company":[{"desc":"test3","id":10},{"desc":"testc","id":30}]}];
var result = mainArray.reduce((c, {name,age,company}) => {
company.forEach(({id,desc}) => (c["company_" + id] = c["company_" + id] || []).push({name,age,desc}));
return c;
}, {});
console.log(result);
You can first create a 1D array using flatMap() and then use reduce() to group
const mainArray = [
{ name: 'a',age: 10, company: [ { desc: 'test1' , id: 6 }, { desc: 'testa' , id: 10 }] },
{ name: 'b',age: 20, company: [ { desc: 'test2' , id: 30 }] },
{ name: 'c',age: 40, company: [ { desc: 'test3' , id: 10 }, { desc: 'testc' , id: 30 }] }
]
const flat = mainArray.flatMap(({company,...rest}) => company.map(a => ({...rest,...a})));
const res = flat.reduce((ac,{id,...rest}) => ((ac[`company_${id}`] || (ac[`company_${id}`] = [])).push(rest),ac),{})
console.log(res)
Explanation
reduce() is method with returns a single value after iterating through all the array. The accumulator i.e ac in above case is set to empty object {}(which is the second argument passed to function)
In each iteration we return the updated accumulator which becomes ac for next iteration. So what we return from function is following expression
((ac[`company_${id}`] || (ac[`company_${id}`] = [])).push(rest),ac)
ac[company_${id}] is using Bracket Notation which takes an expression company_${id}. It is same as
ac["company_" + id]
The above line checks if ac[company_${id}] exists in the ac then push() rest to the it.
If ac[company_${id}] is not created yet they set it to empty array [] then push() the rest to it.
The last part uses comma operator
((ac[`company_${id}`] || (ac[`company_${id}`] = [])).push(rest),ac)
The above whole expression will evaluate to the last value separated by comma , which is ac. So in each iteration we are pushing rest to the respective array and returning ac it the end. The code is equivalent to
const res = flat.reduce((ac,{id,...rest}) => {
//check if company id doesnot exist as key in ac then set it empty array
if(!ac[`company_${id}`]) ac[`company_${id}`] = [];
//push rest(which will be an object with all the keys expect id)
ac[`company_${id}`].push(rest)
//at last return ac
return ac;
})
You can achieve this with Array.reduce and inside it with an Array.forEach over the array of companies like this:
let data = [ { name: 'a',age: 10, company: [ { desc: 'test1' , id: 6 }, { desc: 'testa' , id: 10 }] }, { name: 'b',age: 20, company: [ { desc: 'test2' , id: 30 }] }, { name: 'c',age: 40, company: [ { desc: 'test3' , id: 10 }, { desc: 'testc' , id: 30 }] } ]
let result = data.reduce((r,{ name, age, company }) => {
company.forEach(({ id, desc }) =>
r[`company_${id}`] = (r[`company_${id}`] || []).concat({ name, age, desc }))
return r
}, {})
console.log(result)

Categories

Resources