How to group array obj by? - javascript

I'm new to grouping array obj. I tried the following and I believe I'm getting there but I'm missing something and I don't understand where:
Doing:
const result = data.map(function(item) {
const ditem = dictionary.find(d => d.state == item.state);
if(ditem) {
return {
...item,
"lat": ditem.lat ,
"long": ditem.long
}
}
return item;
});
console.log(result);
const formatted = result.map(area => {
return {
"state": area["state"],
"lat": area["lat"],
"long": area["long"],
"datasets": Object.keys(area)
.map(date => ({ date: area[date], negative: area[date]}))
};
});
Giving me:
[
{
"state": "AK",
"lat": "9875.33.00",
"long": "-8371.42.00",
"datasets": [
{
"date": 20200421,
"negative": 20200421
},
{
"date": "AK",
"negative": "AK"
},
{
"date": 329,
"negative": 329
},
{
"date": 10790,
"negative": 10790...
Expecting example:
0:
State: "AK",
Lat: 45.0732745
Long: 7.680687483
0: date: "2/24/20"
positive: 329
negative: 10790
pending: null
hospitalizedCurrently: 42
hospitalizedCumulative: 36...
1:
date: "2/25/20",
positive: 329
negative: 10790
pending: null
hospitalizedCurrently: 42
hospitalizedCumulative: 36...

This might be the code you are looking for:
const formatted = Object.assign({},result.map(area => {
return {
"state": area["state"],
"lat": area["lat"],
"long": area["long"],
"datasets": Object.assign({},Object.keys(area)
.map(date => ({ date: area[date], negative: area[date]})))
};
}))

Related

How to iterate over JSON files

I am getting JSON data from two links, below is the structure of the files:
Stocks:
[{
"id": "efcd1502-265b-4e39-9a62-d8fbd96d49bb",
"stock_name": "AcelRx Pharmaceuticals, Inc.",
"shareholders": [{
"userId": "5d43449f-17a8-4747-b89a-ec2dd54b83ee",
"number_of_shares": 378
}, {
"userId": "91bef464-b2ee-4c18-8d9d-0781d30a3bcb",
"number_of_shares": 358
}, {
"userId": "c4a0c9ff-b934-4eda-b9fb-bd26afa21561",
"number_of_shares": 351
}, {
"userId": "2a9fd876-334f-425d-9135-4211ca92a886",
"number_of_shares": 499
}]
}]
People:
[{
"id": "20035a09-3820-4f49-bb8f-d947cebee537",
"first_name": "Merell",
"last_name": "Pecht",
"email": "mpecht0#uol.com.br",
"ip_address": "159.113.166.2",
"ssn": "819-97-0464",
"date_of_birth": "12/12/1998",
"address": {
"home": {
"street_number": "862",
"street_name": "Starling",
"street_suffix": "Hill",
"city": "Riverside",
"state": "CA",
"zip": "92519"
},
"work": {
"street_number": "3",
"street_name": "Grayhawk",
"street_suffix": "Circle",
"city": "Tucson",
"state": "AZ",
"zip": "85710"
}
}
}]
Below is my code for replacing the userID present in Stocks' shareholders array with first name and last name from the people file wherever the ID matches.
require("util").inspect.defaultOptions.depth = null;
const axios = require('axios');
async function getPeople(){
const { data } = await axios.get('https://gist.githubusercontent.com/graffixnyc/a1196cbf008e85a8e808dc60d4db7261/raw/9fd0d1a4d7846b19e52ab3551339c5b0b37cac71/people.json')
return data // this will be the array of people objects
}
async function getStocks(){
const { data } = await axios.get('https://gist.githubusercontent.com/graffixnyc/8c363d85e61863ac044097c0d199dbcc/raw/7d79752a9342ac97e4953bce23db0388a39642bf/stocks.json')
return data // this will be the array of people objects
}
async function listShareholders(){
let a = await getPeople();
let b = await getStocks();
let arr = {}
for(j=0;j<b.length;j++){
for(k=0;k<b[j].shareholders.length;k++){
let shareholders = []
let res = {}
for(i=0;i<a.length;i++){
if(b[j].shareholders[k].userId === a[i].id){
res['first_name'] = a[i].first_name
res['last_name'] = a[i].last_name
res['number of shares'] = b[j].shareholders[k].number_of_shares
shareholders.push(res)
arr['id'] = b[j].id
arr['stock_name'] = b[j].stock_name
arr['shareholders'] = shareholders
}
}
}
}
return arr
}
async function bc(){
const address = await listShareholders()
console.log(address)
}
bc()
The output is just one stock with the userID replaced with the name which is the last object in the stocks file. Below is the output I get. I actually need to get all of the stocks with the ID replaced. Not sure what I am doing wrong
{
id: 'efcd1502-265b-4e39-9a62-d8fbd96d49bb',
stock_name: 'AcelRx Pharmaceuticals, Inc.',
shareholders: [
{
first_name: 'Jenni',
last_name: 'Garrish',
'number of shares': 499
}
]
}
Code :
require("util").inspect.defaultOptions.depth = null;
const axios = require('axios');
async function getPeople(){
const { data } = await axios.get('https://gist.githubusercontent.com/graffixnyc/a1196cbf008e85a8e808dc60d4db7261/raw/9fd0d1a4d7846b19e52ab3551339c5b0b37cac71/people.json')
return data // this will be the array of people objects
}
async function getStocks(){
const { data } = await axios.get('https://gist.githubusercontent.com/graffixnyc/8c363d85e61863ac044097c0d199dbcc/raw/7d79752a9342ac97e4953bce23db0388a39642bf/stocks.json')
return data // this will be the array of people objects
}
async function listShareholders(){
let a = await getPeople();
let b = await getStocks();
b.forEach(stockItem => {
stockItem.shareholders = stockItem.shareholders.map(shareHolderItem => {
const person = a.find(e => e.id == shareHolderItem.userId);
return { first_name: person?.first_name,last_name: person?.last_name,number_of_shares: shareHolderItem.number_of_shares}
});
//Keep this if you just want to show mapped shareholder only
stockItem.shareholders = stockItem.shareholders.filter(e => e.first_name !== undefined);
return b
});
}
async function bc(){
const address = await listShareholders()
console.log(address)
}
bc()
You should use Array.map in case you want to change/map to a new structure.
const stocks = [{
"id": "efcd1502-265b-4e39-9a62-d8fbd96d49bb",
"stock_name": "AcelRx Pharmaceuticals, Inc.",
"shareholders": [{
"userId": "5d43449f-17a8-4747-b89a-ec2dd54b83ee",
"number_of_shares": 378
}, {
"userId": "91bef464-b2ee-4c18-8d9d-0781d30a3bcb",
"number_of_shares": 358
}, {
"userId": "c4a0c9ff-b934-4eda-b9fb-bd26afa21561",
"number_of_shares": 351
}, {
"userId": "2a9fd876-334f-425d-9135-4211ca92a886",
"number_of_shares": 499
}, { // my element to match to Merell Pecht
"userId": "20035a09-3820-4f49-bb8f-d947cebee537",
"number_of_shares": 9999
}]
}];
const people = [{
"id": "20035a09-3820-4f49-bb8f-d947cebee537",
"first_name": "Merell",
"last_name": "Pecht",
"email": "mpecht0#uol.com.br",
"ip_address": "159.113.166.2",
"ssn": "819-97-0464",
"date_of_birth": "12/12/1998",
"address": {
"home": {
"street_number": "862",
"street_name": "Starling",
"street_suffix": "Hill",
"city": "Riverside",
"state": "CA",
"zip": "92519"
},
"work": {
"street_number": "3",
"street_name": "Grayhawk",
"street_suffix": "Circle",
"city": "Tucson",
"state": "AZ",
"zip": "85710"
}
}
}];
stocks.forEach(stockItem => {
stockItem.shareholders = stockItem.shareholders.map(shareHolderItem => {
const person = people.find(e => e.id == shareHolderItem.userId);
return {
first_name: person?.first_name,
last_name: person?.last_name,
number_of_shares: shareHolderItem.number_of_shares
}
});
//Keep this if you just want to show mapped shareholder only
stockItem.shareholders = stockItem.shareholders.filter(e => e.first_name !== undefined);
});
console.log(stocks);
Update: Fix function
async function listShareholders(){
let a = await getPeople();
let b = await getStocks();
b.forEach(stockItem => {
stockItem.shareholders = stockItem.shareholders.map(shareHolderItem => {
const person = a.find(e => e.id == shareHolderItem.userId);
return { first_name: person?.first_name,last_name: person?.last_name,number_of_shares: shareHolderItem.number_of_shares}
});
//Keep this if you just want to show mapped shareholder only
stockItem.shareholders = stockItem.shareholders.filter(e => e.first_name !== undefined);
});
return b // <- This row
}
You can do this using Spread Operator and Array.map() functions:
NOTE: I've taken the liberty to simplify the objects for the sake of the example. This should work for the original object as well
const stocks = [{
"id": "efcd1502-265b-4e39-9a62-d8fbd96d49bb",
"stock_name": "AcelRx Pharmaceuticals, Inc.",
"shareholders": [{
"userId": "1",
"number_of_shares": 378
}, {
"userId": "2",
"number_of_shares": 358
}, {
"userId": "3",
"number_of_shares": 351
}, {
"userId": "4",
"number_of_shares": 499
}]
}]
const people = [{
"id": "1",
"first_name": "Tony",
"last_name": "Stark",
},
{
"id": "2",
"first_name": "Steve",
"last_name": "Rogers",
},
{
"id": "3",
"first_name": "Bruce",
"last_name": "Banner",
},
{
"id": "4",
"first_name": "Thor",
"last_name": "Odinson",
}]
const result = stocks.map(stock => {
return {
...stock,
shareholders: stock.shareholders.map(shareHolder => {
const {first_name, last_name} = people.find(person => person.id === shareHolder.userId);
return {
...shareHolder,
first_name,
last_name
}
})
}
})
console.log(JSON.stringify(result, null, 2));

Push a new Object to an object nested Array in React

Am trying to add a new object into my Redux initial States that was dispatched and I cant seem to make it works because am new to it. this is my initial State value
const initialState = {
invoices: data,
filterInvoice: data,
toggleId: "",
singleInvoice: [],
};
the data in front of the invoices is a local Json data am using to populate the states. The Data is an Array of objects. see the data value below
[
{
"id": "RT3080",
"createdAt": "2021-08-18",
"paymentDue": "2021-08-19",
"description": "Re-branding",
"paymentTerms": 1,
"clientName": "Jensen Huang",
"clientEmail": "jensenh#mail.com",
"status": "paid",
"senderAddress": {
"street": "19 Union Terrace",
"city": "London",
"postCode": "E1 3EZ",
"country": "United Kingdom"
},
"clientAddress": {
"street": "106 Kendell Street",
"city": "Sharrington",
"postCode": "NR24 5WQ",
"country": "United Kingdom"
},
"items": [
{
"name": "Brand Guidelines",
"quantity": 1,
"price": 1800.9,
"total": 1800.9
}
],
"total": 1800.9
},
{
"id": "XM9141",
"createdAt": "2021-08-21",
"paymentDue": "2021-09-20",
"description": "Graphic Design",
"paymentTerms": 30,
"clientName": "Alex Grim",
"clientEmail": "alexgrim#mail.com",
"status": "pending",
"senderAddress": {
"street": "19 Union Terrace",
"city": "London",
"postCode": "E1 3EZ",
"country": "United Kingdom"
},
"clientAddress": {
"street": "84 Church Way",
"city": "Bradford",
"postCode": "BD1 9PB",
"country": "United Kingdom"
},
"items": [
{
"name": "Banner Design",
"quantity": 1,
"price": 156.0,
"total": 156.0
},
{
"name": "Email Design",
"quantity": 2,
"price": 200.0,
"total": 400.0
}
],
"total": 556.0
},
]
going on, an object of the same data format would be dispatched into my reducer. so my problem is I dont get how I will add the object to the invoices initialState. My reducer
if (action.type === ActionTypes.DynamicInput) {
let tempInvoice;
//calculate totalValues
const totalAmount = action.payload.items.reduce((acc, curr) => {
const { itemTotal } = curr;
acc += parseFloat(itemTotal);
return acc;
}, 0);
if (action.payload.createdAt) {
const newDate = new Date(action.payload.createdAt).toLocaleDateString();
const paymentDue = addDays(
newDate,
action.payload.paymentTerms
).toLocaleDateString();
if (action.isDraft === true) {
tempInvoice = {
...action.payload,
createdAt: newDate,
paymentDue: paymentDue,
status: "draft",
total: totalAmount,
};
} else {
tempInvoice = {
...action.payload,
createdAt: newDate,
paymentDue: paymentDue,
status: "pending",
total: totalAmount,
};
}
}
// then initalizie the currentStates to add new action.payload objects coming from new invoice
return {
...state,
invoices: { ...state.invoices, tempInvoice },
};
}
I tried using the spread operator to get existing values and assign but it din work
return {
...state,
invoices: [ ...state.invoices, tempInvoice ],
};
after so much debugging and why invoice array is changing, I noticed that TempInvoice is returning empty Objects. I.e It not been populated, Its null. so I refactored my code to look like this
if (action.payload.createdAt) {
const newDate = new Date(action.payload.createdAt).toLocaleDateString();
const paymentDue = addDays(
newDate,
action.payload.paymentTerms
).toLocaleDateString();
if (action.isDraft === false) {
tempInvoice = {
...action.payload,
createdAt: newDate,
paymentDue: paymentDue,
id: getRandomAlphabet(),
status: "draft",
total: totalAmount,
};
} else {
tempInvoice = {
...action.payload,
createdAt: newDate,
paymentDue: paymentDue,
id: getRandomAlphabet(),
status: "pending",
total: totalAmount,
};
}
} else {
if (action.isDraft === false) {
tempInvoice = {
...action.payload,
status: "draft",
id: getRandomAlphabet(),
total: totalAmount,
};
} else {
tempInvoice = {
...action.payload,
status: "pending",
id: getRandomAlphabet(),
total: totalAmount,
};
}
}
return {
...state,
invoices: [...state.invoices, tempInvoice],
}
};

Group and count the nested json response - Angular

Im trying to bind value in Angular Material table, before that i need to process the GET response v
trying to achieve like below(just for understanding)
my faulty code
let filterByLocation = data.reduce((r, { group: location.country, ...object }) => {
var finalArry = r.find(o => o.location === location);
if (!finalArry) r.push(temp = { location, locationObj: [] });
finalArry.locationObj.push(object);
return r;
}, []);
console.log(filterByLocation);
thanks to #Nishant Dixit for his working snippet
const finalResponse = data.response.reduce((r, {
location: {
country: group
},
...object
}) => {
r[group] = r[group] || {
location: group,
locationObj: []
};
r[group].locationObj.push(object);
return r;
}, {});
console.log(finalResponse)
const data = {
"totalRec": 5,
"response": [
{
"employee": {
"uid": 1,
"empName": "Jade"
},
"location": {
"country": "UK",
"subLocation": "London"
},
"department": {
"sector": "IT"
}
},
{
"employee": {
"uid": 2,
"empName": "Mike"
},
"location": {
"country": "UK",
"subLocation": "Manchester"
},
"department": {
"sector": "IT"
}
},
{
"employee": {
"uid": 3,
"empName": "Liya"
},
"location": {
"country": "UK",
"subLocation": "Southampton"
},
"department": {
"sector": "HR"
}
},
{
"employee": {
"uid": 3,
"empName": "Brad"
},
"location": {
"country": "USA",
"subLocation": "Texas"
},
"department": {
"sector": "IT"
}
},
{
"employee": {
"uid": 3,
"empName": "Brad"
},
"location": {
"country": "USA",
"subLocation": "Texas"
},
"department": {
"sector": "NON-IT"
}
}
]
};
but the problem is i'm getting result like
UK : {
location : "UK"
....
}
in html, i don't want to explicitly mention UK with dot operation like below, instead row.location
<ng-container matColumnDef="facility">
<mat-header-cell *matHeaderCellDef mat-sort-header> Facility</mat-header-cell>
<mat-cell *matCellDef="let row"> {{row.UK.location}} </mat-cell>
</ng-container>
could someone tell me how to convert this output like
location: {
country : 'UK'
}
or any random name like
obj: {
location: 'UK'
//rest of values for grouping
}
fiddle
Thanks to every one
You can do something like this:
const countryMap = {};
data.response.forEach(item => {
countryMap[item.location.country] = [ ...( countryMap[item.location.country] || [] ), item];
});
Now, this is how the countryMap will look like:
Now, further to map it to the format you want, you can do this:
const mappedData = Object.entries(countryMap).map(entry => ({
location: entry[0],
response: entry[1]
}));
This will produce mappedData in this format:

Trying to iterate between 2 var obj and merge them

I have:
const dictionary = [
{
"state": "AK",
"lat": "9875.33.00",
"long": "-8371.42.00",
"name": "Alaska"
},
{
"state": "AL",
"lat": "5335.51.00",
"long": "-15124.18.00",
"name": "Alabama"
}
];
const data = [
{
"date": 20200421,
"state": "AK",
},
{
"date": 20200421,
"state": "AL",
}
];
const result = data.map(item => ({...item, lat: dictionary[item.state].lat, long: dictionary[item.state].long }))
console.log(result);
Basically trying to add dictionary as objs per each data where the state matches but I'm having:
Cannot read property 'lat' of undefined
Expecting:
const result = [
{
"date": 20200421,
"state": "AK",
"lat": "9875.33.00",
"long": "-8371.42.00",
},
{
"date": 20200421,
"state": "AL",
"lat": "5335.51.00",
"long": "-15124.18.00",
}
];
I'm trying on fiddle
You cannot access the array items as one whole array. You have to isolate you desired obj. Use this.
const result = data.map(function(item) {
const ditem = dictionary.find(d => d.state == item.state);
if(ditem) {
return {
...item,
"lat": ditem.lat ,
"long": ditem.long
}
}
return item;
});
console.log(result);
You could take an object with state as key and merge new objects by taking name out of the object.
const
dictionary = [{ state: "AK", lat: "9875.33.00", long: "-8371.42.00", name: "Alaska" }, { state: "AL", lat: "5335.51.00", long: "-15124.18.00", name: "Alabama" }],
data = [{ date: 20200421, state: "AK" }, { date: 20200421, state: "AL" }],
states = data.reduce((r, o) => (r[o.state] = o, r), {}),
merged = dictionary.map(({ name, ...o }) => ({ ...(states[o.state] || {}), ...o }));
console.log(merged);
.as-console-wrapper { max-height: 100% !important; top: 0; }
const dictionary = [
{
"state": "AK",
"lat": "9875.33.00",
"long": "-8371.42.00",
"name": "Alaska"
},
{
"state": "AL",
"lat": "5335.51.00",
"long": "-15124.18.00",
"name": "Alabama"
}
];
const data = [
{
"date": 20200421,
"state": "AK",
},
{
"date": 20200421,
"state": "AL",
}
];
let result = dictionary.filter(element =>{
for(let i = 0; i < data.length; i++){
if(data[i].state == element.state) return element;
}
})
console.log(result);

Nested .unionWith, with one unique merge per level

Original data looks like that:
let AddressesBook = [
{
"userName": "Jay12",
"doorNumber": "1512",
"cityID": 19,
"city": "London",
"countryID": 1,
"country": "UK",
"houseType": "private"
},
{
"userName": "Jay12",
"doorNumber": "2003",
"cityID": 14,
"city": "York",
"countryID": 1,
"universe": "UK",
"houseType": "private"
},
{
"userName": "Jay12",
"doorNumber": "435",
"cityID": 31,
"city": "Washington",
"countryID": 2,
"universe": "USA",
"houseType": "private"
},
{
"userName": "Jay12",
"doorNumber": "1123",
"cityID": 18,
"city": "Oxford",
"countryID": 1,
"universe": "UK",
"houseType": "private"
}
];
i was mapping the data hierarchy by relevant unique ID using Lodash and
a suppurated dictionary:
function nestMaker(list, order) {
if (_.isEmpty(order)) return [];
let groups = _.groupBy(list, _.first(order));
return _.map(groups, (children, key) => {
let group = {};
group[_.first(order)] = key;
group.data = nestMaker(children, _.drop(order));
return _.isEmpty(group.data) ? _.omit(group, 'data') : group;
});
}
let hierarchical = nestMaker(AddressesBook, [
"countryID",
"cityID",
"houseType",
"doorNumber"]
);
it works fine, but i would like to have the name relevant to the id in each level of the object.
unfortunately you can't use _.groupBy on two keys. i was thinking about using _.unionWith separately from the first iteration but i couldn't find a way to use it recursively omitting the unnecessary data.
expected output:
let output =
[
{
"countryID": "1",
"country": "UK",
"data": [
{
"cityID": "14",
"city": "York",
"data": [
{
"houseType": "private",
"data": [
{
"doorNumber": "2003"
}
]
}
]
},
{
"cityID": "18",
"city": "Oxford",
"data": [
{
"houseType": "private",
"data": [
{
"doorNumber": "1123"
}
]
}
]
},
{
"cityID": "19",
"city": "London",
"data": [
{
"houseType": "private",
"data": [
{
"doorNumber": "1512"
}
]
}
]
}
]
},
{
"countryID": "2",
"country": "USA",
"data": [
{
"cityID": "31",
"city": "Washington",
"data": [
{
"houseType": "private",
"data": [
{
"doorNumber": "435"
}
]
}
]
}
]
}
];
You can get the 1st item in the group, and extract the name (country, city) from the item:
const AddressesBook = [{"userName":"Jay12","doorNumber":"1512","cityID":19,"city":"London","countryID":1,"country":"UK","houseType":"private"},{"userName":"Jay12","doorNumber":"2003","cityID":14,"city":"York","countryID":1,"country":"UK","houseType":"private"},{"userName":"Jay12","doorNumber":"435","cityID":31,"city":"Washington","countryID":2,"country":"USA","houseType":"private"},{"userName":"Jay12","doorNumber":"1123","cityID":18,"city":"Oxford","countryID":1,"country":"UK","houseType":"private"}];
const nestMaker = (list, order) => {
if (_.isEmpty(order)) return [];
const idKey = _.first(order);
const nameKey = idKey.replace('ID', '');
let groups = _.groupBy(list, idKey);
return _.map(groups, (children, key) => {
const group = {};
const child = _.first(children);
group[idKey] = key;
if(_.has(child, nameKey)) group[nameKey] = child[nameKey];
group.data = nestMaker(children, _.drop(order));
return _.isEmpty(group.data) ? _.omit(group, 'data') : group;
});
}
const hierarchical = nestMaker(AddressesBook, [
"countryID",
"cityID",
"houseType",
"doorNumber"
]);
console.log(hierarchical);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
If the id and the name keys are doesn't follow the same pattern, you can explicitly state them as entry in the order:
const AddressesBook = [{"userName":"Jay12","doorNumber":"1512","cityID":19,"city":"London","countryID":1,"universe":"UK","houseType":"private"},{"userName":"Jay12","doorNumber":"2003","cityID":14,"city":"York","countryID":1,"universe":"UK","houseType":"private"},{"userName":"Jay12","doorNumber":"435","cityID":31,"city":"Washington","countryID":2,"universe":"USA","houseType":"private"},{"userName":"Jay12","doorNumber":"1123","cityID":18,"city":"Oxford","countryID":1,"universe":"UK","houseType":"private"}];
const nestMaker = (list, order) => {
if (_.isEmpty(order)) return [];
const entry = _.first(order);
const [idKey, nameKey] = Array.isArray(entry) ? entry : [entry];
let groups = _.groupBy(list, idKey);
return _.map(groups, (children, key) => {
const group = {};
const child = _.first(children);
group[idKey] = key;
if(_.has(child, nameKey)) group[nameKey] = child[nameKey];
group.data = nestMaker(children, _.drop(order));
return _.isEmpty(group.data) ? _.omit(group, 'data') : group;
});
}
const hierarchical = nestMaker(AddressesBook, [
["countryID", "universe"],
["cityID", "city"],
"houseType",
"doorNumber"
]);
console.log(hierarchical);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
This is a bit manual but does the job.
let AddressesBook = [{
"userName": "Jay12",
"doorNumber": "1512",
"cityID": 19,
"city": "London",
"countryID": 1,
"country": "UK",
"houseType": "private"
},
{
"userName": "Jay12",
"doorNumber": "2003",
"cityID": 14,
"city": "York",
"countryID": 1,
"country": "UK",
"houseType": "private"
},
{
"userName": "Jay12",
"doorNumber": "435",
"cityID": 31,
"city": "Washington",
"countryID": 2,
"country": "USA",
"houseType": "private"
},
{
"userName": "Jay12",
"doorNumber": "1123",
"cityID": 18,
"city": "Oxford",
"countryID": 1,
"country": "UK",
"houseType": "private"
}
];
database = []
AddressesBook.forEach(a => {
doesExist = database.some(d => (d.countryID == a.countryID))
if (doesExist) {
let instance = database.filter(d => d.countryID == a.countryID)[0]
instance.data.push({
"cityID": a.cityID,
"city": a.city,
"data": [{
"houseType": a.houseType,
"data": [{
"doorNumber": a.doorNumber
}]
}]
})
} else {
database.push({
"countryID": a.countryID,
"country": a.country,
"data": [{
"cityID": a.cityID,
"city": a.city,
"data": [{
"houseType": a.houseType,
"data": [{
"doorNumber": a.doorNumber
}]
}]
}]
})
}
})
console.log(database)

Categories

Resources