Can not access a key value in node object - javascript

I can't even figure out how this is possible
when I do this:
console.error(order.Items[i]);
I get this:
{ ItemURL: '',
IsBundle: false,
GiftTaxPrice: '0',
GiftPrice: '0',
GiftNotes: null,
GiftMessage: null,
RecyclingFee: 0,
ShippingTaxPrice: 0,
ShippingPrice: 6,
TaxPrice: 0,
UnitPrice: 3,
Quantity: 1,
Title: 'HICKIES TEST PRODUCT',
Sku: 'PLSB_TEST_PRODUCT',
SiteListingID: '30000418',
SiteOrderItemID: '',
ProductID: 72176,
OrderID: 100152,
ProfileID: 12021605,
ID: 156,
CustomFields: [],
Adjustments: [],
FulfillmentItems: [],
Promotions: [] }
But for some reason when I try to access Sku with
console.error(order.Items[i].Sku);
I get:
undefined
Yet magically for some reason
console.error(order.Items[i].Quantity);
or
console.error(order.Items[i].UnitPrice);
Print:
1
and
3
Respectively
---EDIT
As requested
for (var i = 0; i < order.Items.length; i++) {
formatedOrder['Subtotal'] += parseInt(order.Items[i].Quantity) * parseFloat(order.Items[i].UnitPrice);
console.error(order.Items[i]);
console.error(order.Items[i].Sku);
console.error(order.Items[i]['Sku']);
formatedOrder["OrderLines"].push({
"Product": order.Items[i].Sku,
"Quantity": parseInt(order.Items[i].Quantity),
"Price": parseFloat(order.Items[i].UnitPrice)
});
}
As Requested the Items Array :
[{ ItemURL: '',
IsBundle: false,
GiftTaxPrice: '0',
GiftPrice: '0',
GiftNotes: null,
GiftMessage: null,
RecyclingFee: 0,
ShippingTaxPrice: 0,
ShippingPrice: 6,
TaxPrice: 0,
UnitPrice: 3,
Quantity: 1,
Title: 'HICKIES TEST PRODUCT',
Sku: 'PLSB_TEST_PRODUCT',
SiteListingID: '30000418',
SiteOrderItemID: '',
ProductID: 72176,
OrderID: 100152,
ProfileID: 12021605,
ID: 156,
CustomFields: [],
Adjustments: [],
FulfillmentItems: [],
Promotions: [] }]

Try this, I have no reason to use console.error() use console.log() instead
for (var i = 0; i < order.Items.length; i++) {
formatedOrder['Subtotal'] += parseInt(order.Items[i].Quantity) * parseFloat(order.Items[i].UnitPrice);
console.log(order.Items[i]);
console.log(order.Items[i].Sku);
console.log(order.Items[i]['Sku']);
formatedOrder["OrderLines"].push({
"Product": order.Items[i].Sku,
"Quantity": parseInt(order.Items[i].Quantity),
"Price": parseFloat(order.Items[i].UnitPrice)
});
}
Huh surprising !!!

JSON.Stringify() Solved the issue, It turns out the object was not a flat JSON object like I expected but some other object that did not allow me to just access the values

Related

How to perform multiple nested Lodash GroupBys on a tree like structure?

Say I have a data structure like so.
child: [
{
typeOfPackage: 'subSub',
parents: '/Test123/Diet/',
itemName: '250 ML',
pricePerItem: 150,
quantity: 0,
quantityType: '123',
description: '5',
avgTimeTaken: 0,
images: [],
isEnabled: true,
inventory: [],
equipment: [],
_id: 617f9efdf0347931684888fd
},
{
typeOfPackage: 'sub',
parents: '/Test123/',
itemName: 'Regular',
pricePerItem: 0,
quantity: 0,
quantityType: '1',
description: '1',
avgTimeTaken: 1,
images: [],
isEnabled: true,
inventory: [],
equipment: [],
_id: 617f9efdf0347931684888fe
},
{
typeOfPackage: 'subSub',
parents: '/Test123/Reg3/',
itemName: '500ML',
pricePerItem: 123,
quantity: 0,
quantityType: '12',
description: '123',
avgTimeTaken: 51,
images: [],
isEnabled: true,
inventory: [],
equipment: [],
_id: 617f9efdf0347931684888ff
}
]
I intend to transform this data by splitting parents. And my intended result looks as follows:
child: [
{
itemName: 'Test123',
subPackages: [
{
itemName: 'Diet',
subSubPackages: [{
typeOfPackage: 'subSub',
parents: '/Test123/Diet/',
itemName: '250 ML',
pricePerItem: 150,
quantity: 0,
quantityType: '123',
description: '5',
avgTimeTaken: 0,
images: [],
isEnabled: true,
inventory: [],
equipment: [],
}]
},
{
itemName: 'Regular',
typeOfPackage: 'sub',
parents: '/Test123/',
pricePerItem: 0,
quantity: 0,
quantityType: '1',
description: '1',
avgTimeTaken: 1,
images: [],
isEnabled: true,
inventory: [],
equipment: [],
subSubPackages: [],
},
{
itemName: 'Reg3',
subSubPackages: [
{
typeOfPackage: 'subSub',
parents: '/Test123/Reg3/',
itemName: '500ML',
pricePerItem: 123,
quantity: 0,
quantityType: '12',
description: '123',
avgTimeTaken: 51,
images: [],
isEnabled: true,
inventory: [],
equipment: [],
_id: 617f9efdf0347931684888ff
}
]
},
]
}
]
I tried using lodash's chain and groupBy but I could only get as far as grouping it by the first itemName (Test123). I could not figure out how to do further grouping inside that without using a custom for loop and map methods and that too confused me.
You could split parents and build a nested structure.
This approach takes an shadow object for a faster access to same named parents and returns only the payload without organizing structure.
If you like to use subPackages or subSubPackages, you could take a function for generating this key along with the actuyl nesting level. For later processing data, I recommend to use only generic names, like children for every level.
const
getSub = level => `sub${'Sub'.repeat(level)}Level`,
data = [{ typeOfPackage: 'subSub', parents: '/Test123/Diet/', itemName: '250 ML', pricePerItem: 150, quantity: 0, quantityType: '123', description: '5', avgTimeTaken: 0, images: [], isEnabled: true, inventory: [], equipment: [], _id: '617f9efdf0347931684888fd' }, { typeOfPackage: 'sub', parents: '/Test123/', itemName: 'Regular', pricePerItem: 0, quantity: 0, quantityType: '1', description: '1', avgTimeTaken: 1, images: [], isEnabled: true, inventory: [], equipment: [], _id: '617f9efdf0347931684888fe' }, { typeOfPackage: 'subSub', parents: '/Test123/Reg3/', itemName: '500ML', pricePerItem: 123, quantity: 0, quantityType: '12', description: '123', avgTimeTaken: 51, images: [], isEnabled: true, inventory: [], equipment: [], _id: '617f9efdf0347931684888ff' }],
result = data
.reduce((r, o) => {
o
.parents
.split('/')
.filter(Boolean)
.reduce((t, itemName, i) => {
if (!t[itemName]) {
t[itemName] = { _: [] };
t._.push({ itemName, [getSub(i)]: t[itemName]._ });
}
return t[itemName];
}, r)
._
.push(o);
return r;
}, { _: [] })
._;
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

how to simplify the length of the state in react js

import { OrderSummary } from "#/services/order/data";
Below is my state declaration
let [orderSummary, setOrderSummary] = useState<OrderSummaryResponse>({
Id: 0,
TableId: 0,
TableName: '',
MerchantId: 0,
StoreId: 0,
StoreName: '',
BrandName: '',
IsUnifyQR: false,
Discount: 0,
ServiceCharge: 0,
GST: 0,
RoundingAdjustment: 0,
TotalAmount: 0,
SubTotalAmount: 0,
ServiceChargeAmount: 0,
GSTAmount: 0,
CreatedAt: '',
Items: [
{
MerchantId: 0,
StoreId: 0,
StoreName: '',
ItemId: 0,
ProductId: 0,
ProductName: '',
TotalAmount: 0,
Quantity: 0,
Note: '',
Choices: [
{
OptionSelectedName: '',
ProductOptionId: 0,
OptionSelected: null,
MultiOptionsSelected: null,
OneChoiceWithValueSelected: {
OptionSelected: 0,
Quantity: 0,
Price: 0,
},
MultioptionWithValueSelected: [],
},
],
},
],
Categories: [''],
});
if I have a few usestate like above, my code looks very lengthy how to simplify that.
getting error if I use like this
let [orderSummary, setOrderSummary] = useState<OrderSummary>({})
let [orderSummary, setOrderSummary] = useState<OrderSummary>({} as any)
You can use type like this:
let [orderSummary, setOrderSummary] = useState<OrderSummary | null>(null)
And when you want to use orderSummary. You can add optional chaining like this:
orderSummary?.StoreId

Sum on two values in an array of objects then insert into another array of objects

I have an array of objects called stores:
stores = [
{
storeId: 1,
city: "San Francisco",
state: "CA",
},
{
storeId: 2,
city: "Seattle",
state: "WA",
},
{
storeId: 3,
city: "Vancouver",
state: "BC",
},
{
storeId: 4,
city: "Los Angeles",
state: "CA",
},
]
and another array of objects called items:
items = [
{
itemId: 1,
cost: 10,
price: 20,
sold: false,
_storeId: 1,
},
{
itemId: 2,
cost: 10,
price: 20,
sold: false,
_storeId: 1,
},
{
itemId: 3,
cost: 5,
price: 12,
sold: true,
_storeId: 2,
},
{
itemId: 4,
cost: 12,
price: 20,
sold: false,
_storeId: 3,
},
{
itemId: 5,
cost: 2,
price: 10,
sold: false,
_storeId: 4,
},
{
itemId: 6,
cost: 10,
price: 50,
sold: true,
_storeId: 4,
},
]
I want to sum the following categories by store:
TotalCost
TotalPrice
Then count the total items by store:
TotalItems
Then count the subtotal items sold by store:
SoldItems
so my final store array looks something like this:
storesUpdated = [
{
storeId: 1,
city: "San Francisco",
state: "CA",
totalCost: 20,
totalPrice: 40,
countTotalItems: 2,
countSoldItems: 0
},
{
storeId: 2,
city: "Seattle",
state: "WA",
totalCost: 5,
totalPrice: 12,
countTotalItems: 1,
countSoldItems: 1
},
{
storeId: 3,
city: "Vancouver",
state: "BC",
totalCost: 12,
totalPrice: 20,
countTotalItems: 1,
countSoldItems: 0
},
{
storeId: 4,
city: "Los Angeles",
state: "CA",
totalCost: 12,
totalPrice: 60,
countTotalItems: 2,
countSoldItems: 1
},
]
I've tried mapping over stores array but got stuck here:
const storesUpdated = stores.map((store) => {
= {}
items.forEach(item => {
if (item._storeId === store.storeId) {
return totalCost {
'storeId' : item.storeId,
}
}
})
})
Any ideas? Many thanks.
const stores = [{storeId:1,city:"San Francisco",state:"CA",},{storeId:2,city:"Seattle",state:"WA",},{storeId:3,city:"Vancouver",state:"BC",},{storeId:4,city:"Los Angeles",state:"CA",},]
const items = [{itemId:1,cost:10,price:20,sold:!1,_storeId:1,},{itemId:2,cost:10,price:20,sold:!1,_storeId:1,},{itemId:3,cost:5,price:12,sold:!0,_storeId:2,},{itemId:4,cost:12,price:20,sold:!1,_storeId:3,},{itemId:5,cost:2,price:10,sold:!1,_storeId:4,},{itemId:6,cost:10,price:50,sold:!0,_storeId:4,},]
const storesUpdated = stores.map((store) => {
const updatedStore = { ...store,
totalCost: 0,
totalPrice: 0,
countTotalItems: 0,
countSoldItems: 0
}
items.forEach(item => {
if (item._storeId === store.storeId) {
updatedStore.totalCost += item.cost
updatedStore.totalPrice += item.price
updatedStore.countTotalItems += 1
updatedStore.countSoldItems += item.sold ? 1 : 0
}
})
return updatedStore
})
console.log(storesUpdated)
If you want to only loop over your data once, you could perform the merge in two steps:
Create the "empty" stores and index them by id in a single reduce: (one loop over stores)
const Store = (data) => ({ /* ... */ });
const storesById = storeData => storeData.reduce(
(map, sd) => Object.assign(map, { [sd.storeId]: Store(sd) }),
{}
);
Loop over the items and merge them in to the corresponding store: (one loop over items)
const addItemToStoreMap = (storeMap, item) => ({
...storeMap,
[item._storeId]: addItemToStore(storeMap[item._storeId], item)
});
Note that creating all the new objects using the object spread syntax kind of cancels out the performance boost, but it's still nice that this is O(n + m) instead of O(n * m).
Putting it all together:
const storeData = [{storeId:1,city:"San Francisco",state:"CA",},{storeId:2,city:"Seattle",state:"WA",},{storeId:3,city:"Vancouver",state:"BC",},{storeId:4,city:"Los Angeles",state:"CA",},]
const itemData = [{itemId:1,cost:10,price:20,sold:!1,_storeId:1,},{itemId:2,cost:10,price:20,sold:!1,_storeId:1,},{itemId:3,cost:5,price:12,sold:!0,_storeId:2,},{itemId:4,cost:12,price:20,sold:!1,_storeId:3,},{itemId:5,cost:2,price:10,sold:!1,_storeId:4,},{itemId:6,cost:10,price:50,sold:!0,_storeId:4,},]
const { Store, addItemToStoreMap, storesById } = storeUtils();
// Loop over the stores *once*, loop over the items *once*
// During the second loop, add items to the right stores
const itemsByStoreId = itemData.reduce(addItemToStoreMap, storesById(storeData));
console.log(Object.values(itemsByStoreId));
function storeUtils() {
// Our client-side model for a Store
const Store = ({ storeId, city, state }) => ({
storeId,
city,
state,
totalCost: 0,
totalPrice: 0,
countTotalItems: 0,
countSoldItems: 0
});
// Merge logic for adding an item to a store
// Can be used in a reduce on a list of items seeded with a store
const addItemToStore = (store, item) => ({
...store,
totalCost: store.totalCost + item.cost,
totalPrice: store.totalPrice + item.price,
countTotalItems: store.countTotalItems + 1,
countSoldItems: store.countSoldItems + item.sold
});
// Selects the right store for an item and returns a new
// map with the updated store
const addItemToStoreMap = (storeMap, item) => ({
...storeMap,
[item._storeId]: addItemToStore(storeMap[item._storeId], item)
});
// Converts raw data to Store objects and indexes them by their id
const storesById = storeData => storeData.reduce(
(map, sd) => Object.assign(map, { [sd.storeId]: Store(sd) }),
{}
);
return { Store, addItemToStoreMap, storesById };
};

What's the most efficent way to populate an a property of an array of objects with a larger array with data?

I have a small array of objects with properties, like so:
[
{
topicName: 'Clicks',
topic: 1,
dates: [ <PLACE VALUES HERE> ],
},
{
topicName: 'Cost',
topic: 2,
dates: [ <PLACE VALUES HERE> ],
},
];
Then I have a large array of objects that I wish to extract some of the properties from in to the above dates array.
Here's what the data I wish to extract from:
[
{
"date": "2014-02-01",
"device": "Computer",
"match-type": "NA",
"clicks": 66,
"revenue": 1037,
"conversions": 2,
"cost": 284.35,
"impressions": 5330,
"ROI": 3.64691401441885
},
{
"date": "2014-02-01",
"device": "Tablet",
"match-type": "NA",
"clicks": 38,
"revenue": 587,
"conversions": 2,
"cost": 194.01000000000005,
"impressions": 1934,
"ROI": 3.025617236224936
},
{
"date": "2014-02-02",
"device": "Tablet",
"match-type": "NA",
"clicks": 40,
"revenue": 587,
"conversions": 2,
"cost": 190,
"impressions": 1934,
"ROI": 3.025617236224936
},
]
Now I need the data from all of the members of the last array and insert that releveant data for the particular object in the first array (totalling where necessary), like so:
[
{
topicName: 'Clicks',
topic: 1,
dates: [
{
date: '2014-02-01',
value: 104
},
{
date: '2014-02-02',
value: 40
}
],
},
{
topicName: 'Cost',
topic: 2,
dates: [
{
date: '2014-02-01',
value: 284,3519401
},
{
date: '2014-02-02',
value: 190
}
],
},
];
The target is the latest version of Chrome and I'm using Webpack with Babel so all the latest stuff is available.
Assuming the last dataset can be pretty large, what's the most efficient way to go about this?
[EDIT]
This is what I've come up with so far:
const dataAdapter = rawData => {
const topics = ['clicks', 'revenue', 'cost', 'roi'];
const topicsData = topics.map((topic, index) => {
const thisTopic = {};
thisTopic.topicName = topic;
thisTopic.topic = index;
thisTopic.dates = [];
return thisTopic;
});
const convertedData = topicsData.map(topicData => {
const thisTopic = topicData;
const map = new Map();
rawData.forEach(elem => {
map.set(elem.date, (map.get(elem.date) || 0) + elem[[thisTopic.topicName]]);
});
thisTopic.dates = Array.from(map);
return thisTopic;
});
return convertedData;
};
Thanks,
/J
You could take an object as reference to the wanted keys and date. Then iterate data and check if a reference to a result set exists. If not, create a new result set.
var result = [{ topicName: 'Clicks', topic: 1, dates: [], }, { topicName: 'Cost', topic: 2, dates: [], }],
data = [{ date: "2014-02-01", device: "Computer", "match-type": "NA", clicks: 66, revenue: 1037, conversions: 2, cost: 284.35, impressions: 5330, ROI: 3.64691401441885 }, { date: "2014-02-01", device: "Tablet", "match-type": "NA", clicks: 38, revenue: 587, conversions: 2, cost: 194.01000000000005, impressions: 1934, ROI: 3.025617236224936 }, { date: "2014-02-02", device: "Tablet", "match-type": "NA", clicks: 40, revenue: 587, conversions: 2, cost: 190, impressions: 1934, ROI: 3.025617236224936 }],
hash = { clicks: { _: result[0].dates }, cost: { _: result[1].dates }, };
data.forEach(function (o) {
['clicks', 'cost'].forEach(function (k) {
if (!hash[k][o.date]) {
hash[k][o.date] = { date: o.date, value: o[k] };
hash[k]._.push(hash[k][o.date]);
return;
}
hash[k][o.date].value += o[k];
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Assuming your data is in data variable and topics are in topics variable. This solution uses only javascript builtin objects.
const getPropDateMap = (obj, prop) => obj
.reduce((accObj, item) => {
return Object.assign(accObj, {
[item.date]: item.clicks + (accObj[item.date] || 0)
})
}, {})
topics.forEach(topic => {
topic.dates = Object
.entries(getPropDateMap(data, topic.topicName.toLowerCase()))
.map(entry => ({date: entry[0], value: entry[1]}))
})

Move child JSON objects to their own object with parent ID

I am pretty new to JavaScript, and am working with Node.JS to access an API and store the response in a SQL Server. I am using the "request" and "mssql" Node packages. I am not attached to these, they just seemed to be what I needed and have good documentation and support.
My question: I have the JSON response from the API in the following format:
requests = [ {
url: 'https://domain.zendesk.com/api/v2/requests/2.json',
id: 2,
status: 'closed',
priority: 'normal',
type: 'incident',
subject: 'Test Ticket',
description: 'Test ticket',
organization_id: 10101010101,
via: {
channel: 'email',
source: {
from: {
address: 'bill.bob#domain.com',
name: 'Bill Bob'
},
to: {
name: 'Company Helpdesk',
address: 'testzendesk#domain.com'
},
rel: null
},
},
custom_fields:[
{ id: 31368658, value: null },
{ id: 29221487, value: null },
{ id: 31636418, value: null },
{ id: 29498078, value: null },
{ id: 31659217, value: null }
],
requester_id: 2020202020,
collaborator_ids: [],
is_public: true,
due_at: null,
can_be_solved_by_me: false,
created_at: '2015-03-05T05:55:22Z',
updated_at: '2015-03-12T05:01:51Z',
recipient: 'testzendesk#domain.com',
followup_source_id: null,
assignee_id: 30303030303,
ticket_form_id: null,
fields: [
{ id: 31368658, value: null },
{ id: 29221487, value: null },
{ id: 31636418, value: null },
{ id: 29498078, value: null },
{ id: 31659217, value: null }
]
},
{
url: 'https://domain.zendesk.com/api/v2/requests/2.json',
id: 3,
status: 'closed',
priority: 'normal',
type: 'incident',
subject: 'Test Ticket',
description: 'Test ticket',
organization_id: 10101010101,
via: {
channel: 'email',
source: {
from: {
address: 'bill.bob#domain.com',
name: 'Bill Bob'
},
to: {
name: 'Company Helpdesk',
address: 'testzendesk#domain.com'
},
rel: null
}
},
custom_fields: [
{ id: 31368658, value: null },
{ id: 29221487, value: null },
{ id: 31636418, value: null },
{ id: 29498078, value: null },
{ id: 31659217, value: null }
],
requester_id: 2020202020,
collaborator_ids: [],
is_public: true,
due_at: null,
can_be_solved_by_me: false,
created_at: '2015-03-05T05:55:22Z',
updated_at: '2015-03-12T05:01:51Z',
recipient: 'testzendesk#domain.com',
followup_source_id: null,
assignee_id: 30303030303,
ticket_form_id: null,
fields: [
{ id: 31368658, value: null },
{ id: 29221487, value: null },
{ id: 31636418, value: null },
{ id: 29498078, value: null },
{ id: 31659217, value: null }
]
} ];
I need to pull the children objects out, i.e. the "via", "custom_fields" and "fields" with the parent IDs. So for the first object, each of the "via" children objects would also have the ID of 2, and would have "channel", "source", and "ID" elements.
Something like this:
parents:
[
{
url: 'https://domain.zendesk.com/api/v2/requests/2.json',
id: 2,
status: 'closed',
priority: 'normal',
type: 'incident',
subject: 'Test Ticket',
description: 'Test ticket',
organization_id: 10101010101,
requester_id: 2020202020,
collaborator_ids: [],
is_public: true,
due_at: null,
can_be_solved_by_me: false,
created_at: '2015-03-05T05:55:22Z',
updated_at: '2015-03-12T05:01:51Z',
recipient: 'testzendesk#domain.com',
followup_source_id: null,
assignee_id: 30303030303,
ticket_form_id: null
},
{ url: 'https://domain.zendesk.com/api/v2/requests/2.json',
id: 3,
status: 'closed',
priority: 'normal',
type: 'incident',
subject: 'Test Ticket',
description: 'Test ticket',
organization_id: 10101010101,
requester_id: 2020202020,
collaborator_ids: [],
is_public: true,
due_at: null,
can_be_solved_by_me: false,
created_at: '2015-03-05T05:55:22Z',
updated_at: '2015-03-12T05:01:51Z',
recipient: 'testzendesk#domain.com',
followup_source_id: null,
assignee_id: 30303030303,
ticket_form_id: null
}
]
via:
[
{
channel: 'email',
parent_id: 2
},
{
channel: 'email',
parent_id: 3
}
]
via_source_from:
[
{
address: 'bill.bob#domain.com',
name: 'Bill Bob',
parent_id: 2
},
{
address: 'bill.bob#domain.com',
name: 'Bill Bob',
parent_id: 2
}
]
via_source_to:
[
{
name: 'Company Helpdesk',
address: 'testzendesk#domain.com',
parent_id: 2
},
{
name: 'Company Helpdesk',
address: 'testzendesk#domain.com',
parent_id: 2
}
]
custom_fields:
[
{ parent_id: 2, id: 31368658, value: null },
{ parent_id: 2, id: 29221487, value: null },
{ parent_id: 2, id: 31636418, value: null },
{ parent_id: 2, id: 29498078, value: null },
{ parent_id: 2, id: 31659217, value: null },
{ parent_id: 3, id: 31368658, value: null },
{ parent_id: 3, id: 29221487, value: null },
{ parent_id: 3, id: 31636418, value: null },
{ parent_id: 3, id: 29498078, value: null },
{ parent_id: 3, id: 31659217, value: null }
]
fields:
[
{ parent_id: 2, id: 31368658, value: null },
{ parent_id: 2, id: 29221487, value: null },
{ parent_id: 2, id: 31636418, value: null },
{ parent_id: 2, id: 29498078, value: null },
{ parent_id: 2, id: 31659217, value: null },
{ parent_id: 3, id: 31368658, value: null },
{ parent_id: 3, id: 29221487, value: null },
{ parent_id: 3, id: 31636418, value: null },
{ parent_id: 3, id: 29498078, value: null },
{ parent_id: 3, id: 31659217, value: null }
]
I have searched around, and have not found anything that would allow me to do this.
Thanks a bunch!
You can do something like this, there isn't much to describe but still if couldn't understand anything in below code, please comment.
I haven't manipulated the parents object, but you can delete the desired fields yourself. you can refer to this link. But remember to manipulate after cloning the object because delete operator mutate the original object.
let
parents = [],
via = [],
via_source_from = [],
via_source_to = [],
custom_fields = [],
fields = [];
requests.forEach( record => {
let pid = record.id;
parents = [ ...parents, record ];
via = [ ...via, Object.assign({}, { parent_id: pid, channel: record.via.channel } ) ];
via_source_from = [ ...via_source_from, Object.assign({}, { parent_id: pid }, record.via.source.from ) ]
via_source_to = [ ...via_source_to, Object.assign({}, { parent_id: pid }, record.via.source.to ) ]
custom_fields = [ ...custom_fields, ...record.custom_fields.map( f => { return Object.assign({}, f, { parent_id: pid }) } ) ]
fields = [ ...fields, ...record.fields.map( f => { return Object.assign({}, f, { parent_id: pid }) } ) ]
});
console.log("parent: ", parent);
console.log("via: ", via);
console.log("via_source_from: ", via_source_from);
console.log("via_source_to: ", via_source_to);
console.log("custom_fields: ", custom_fields);
console.log("fields: ", fields);
Update
I have just created an empty array in start to add the specific data on each iteration of requests. Then concatenate the array with relevant data using mainly four concepts, given below.
Spread Operator
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
var arr3 = [...arr1, ...arr2]; // returns new array [0, 1, 2, 3, 4, 5]
var arr4 = [...arr3, 6]; // returns new array [0, 1, 2, 3, 4, 5, 6]
This is new spread operator of javascript. You can refer this link for better understanding. In case of array, it works same as array.concat just more clean syntax.
Object assign
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
var obj = { a: 1 };
var copy = Object.assign({}, obj, { b: 2 }); // we can add as many object as we need.
copy.c = 3;
console.log(obj); // { a: 1 }
console.log(copy); // { a: 1, b: 2, c: 3 }
A great way to clone the object without having a reference to the original object. In short, to create immutable object. You can refer this link for better understanding.
Array.prototype.map()
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
var numbers = [1, 5, 10, 15];
var doubles = numbers.map(function(x) {
return x * 2;
});
// doubles is now [2, 10, 20, 30]
// numbers is still [1, 5, 10, 15]
Remember, it returns a new array and doesn't affect the original array. You have to return something from internal function else, you will have undefined at that index in final array. You can refer this link for better understanding.
Arrow Function
An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target.
[ 'hi', 'ola', 'hello' ].map( greet => greet.length );
// returns [ 2, 3, 5 ]
Just a shorter syntax for writing a function. One main point is it doesn't bind its own this unlike function keyword, it really helps in defining scope of the this. You can refer this link for better understanding.

Categories