I have a simply array and want to loop through the array which have some same key and value, and i want to make a group of those values which are the same and put the related item under that.
export class AppComponent implements OnInit {
data = [
{
'con': 'Usa',
'city': 'ny',
'town':'as'
},
{
'con': 'Ger',
'city': 'ber',
'town':'zd'
},
{
'con': 'Usa',
'city': 'la',
'town':'ss'
}
];
array: any[] = [];
ngOnInit() {
this.array = this.data;
}
}
html:
<div *ngFor="let item of array ">
<h3>{{item.con}}</h3>
<p>{{item.city}}</p>
<p>{{item.town}}</p>
<hr>
</div>
and i have a following result:
Usa
ny
as
-----
Ger
ber
zd
-----
Usa
la
ss
-----
but what i really wants is to make a group of those country with the same name and display the related cities and town under that with the following format:
[{
"con": "usa",
"area": [{
"city": "ny",
"town": "as"
}, {
"city": "la",
"town": "ss"
}]
},
{
"con": "ger",
"area": [{
"city": "ber",
"town": "zd"
}]
}
]
Transform the data to an array with the consolidated objects, where the cities properties have arrays, like so
[
{ con: "Usa": cities: ["ny", "la"] },
{ con: "Ger", cities: ["ber"] }
]
You can build that data structure as follows:
this.array = Array.from(
this.data.reduce(
(map, {con, city}) => map.set(con, (map.get(con) || []).concat(city)),
new Map
), ([con, cities]) => ({ con, cities })
);
Then the HTML part becomes:
<div *ngFor="let item of array ">
<h3>{{item.con}}</h3>
<div *ngFor="let city of item.cities ">
<p>{{city}}</p>
</div>
<hr>
</div>
You can sort your JSON before passing to angular ngFor as bellow,
data = [
{
'con': 'Usa',
'city': 'ny'
},
{
'con': 'Ger',
'city': 'ber'
},
{
'con': 'Usa',
'city': 'la'
}
];
var expectedResult = data.sort(function (a, b) {
return a.con.localeCompare(b.con);
});
console.log(expectedResult)
//OR
// change order as return b.con.localeCompare(a.con);
Related
I am facing an issue with an excel file. I receive some data from the DB and the user should be able to replace that data with a spreadsheet that looks like this:
This is how the data comes from the DB and how the excel file should be finally formatted:
"employers": [{
"id": "4147199311345513",
"shifts": [{
"url": "https://zoom.com/983493unsdkd/",
"days": "Mon,Tue,Wed,Thu,Fri",
"name": "Morning",
"endTime": "12:00",
"timezone": "CST",
"startTime": "8:00"
}, {
"url": "https://zoom.com/983493unsdkd/",
"days": "Mon,Tue,Wed,Thu,Fri",
"name": "Afternoon",
"endTime": "12:00",
"timezone": "CST",
"startTime": "8:00"
}],
"employerUrl": "http://www.google.com",
"employerName": "AT&T",
"employerUrlText": "URL Text",
"employerLogoSmall": "assets/images/att-logo.png",
"employerDescription": "AT&T is a world premier employer with a bunch of stuff here and there."
}, {
"id": "3763171269270198",
"shifts": [{
"url": "https://zoom.com/983493unsdkd/",
"days": "Mon,Tue,Wed,Thu,Fri",
"name": "Morning",
"endTime": "12:00",
"timezone": "CST",
"startTime": "8:00"
}, {
"url": "https://zoom.com/983493unsdkd/",
"days": "Mon,Tue,Wed,Thu,Fri",
"name": "Afternoon",
"endTime": "12:00",
"timezone": "CST",
"startTime": "8:00"
}],
"employerUrl": "http://www.google.com",
"employerName": "AT&T",
"employerUrlText": "URL Text",
"employerLogoSmall": "assets/images/att-logo.png",
"employerDescription": "AT&T is a world premier employer with a bunch of stuff here and there."
}]
So I need to take that spreadsheet and format it to look like that JSON above. All of this with Javascript/React.
This is what I have so far to format my excel file and render it:
const [excelData, setExcelData] = useState({ rows: [], fileName: "" });
const fileHandler = (event) => {
let fileObj = event.target.files[0];
ExcelRenderer(fileObj, (err, resp) => {
if (err) {
console.log(err);
} else {
let newRows = [];
let shiftRows = [];
console.log(resp.rows);
resp.rows.slice(1).map((row, index) => {
if (row && row !== "undefined") {
return newRows.push({
key: index,
employer: {
name: row[0],
description: row[1],
employerUrl: row[2],
employerUrlText: row[3],
shifts: shiftRows.push({ shift: row[2] }),
},
});
}
return false;
});
setExcelData({ rows: newRows, fileName: fileObj.name });
}
});
};
That console.log above (console.log(resp.rows)) returns this:
Where the first row are the headers of the excel file.
And the code above ends up like this and it should be exactly as the JSON I mentioned:
rows: [
{
key: 0,
employer: {
name: 'AT&T',
description: 'AT&T is a world premier employer with a bunch of stuff here and there.',
shifts: 1
}
},
{
key: 1,
employer: {
shifts: 2
}
},
{
key: 2,
employer: {
shifts: 3
}
},
{
key: 3,
employer: {
shifts: 4
}
},
{
key: 4,
employer: {
name: 'Verizon',
description: 'Verizon is a world premier employer with a bunch of stuff here and there.',
shifts: 5
}
},
{
key: 5,
employer: {
shifts: 6
}
},
{
key: 6,
employer: {
shifts: 7
}
},
{
key: 7,
employer: {
shifts: 8
}
}
],
fileName: 'EmployerChats.xlsx',
false: {
rows: [
{
url: 'https://www.youtube.com/kdfjkdjfieht/',
title: 'This is a video',
thumbnail: '/assets/images/pages/5/links/0/link.png',
description: 'This is some text'
},
{
url: 'https://www.youtube.com/kdfjkdjfieht/',
title: 'This is a video',
thumbnail: '/assets/images/pages/5/links/1/link.png',
description: 'This is some text'
}
]
},
I am using this plugin to help me render the excel file: https://www.npmjs.com/package/react-excel-renderer
Any ideas on what can I do to make format the spreadsheet data as the JSON?
Please notice those empty rows.
For example every time there is a new employer name, that's a new row or item in the array, then all of the columns and rows below and after Shift Name is a new nested array of objects. Hence, this file contains an array with a length of 2 and then it contains another array of items when it hits the Shift Name column.
Is it clear?
1st of all - you don't need to follow 'original', class based setState. In FC you can just use two separate useState.
const [rows, setRows] = useState([]);
const [fileName, setFileName] = useState("");
Data conversion
I know that you need a bit different workflow, but this can be usefull (common point - data structure), too - as conversion guide, read on.
You don't need to use ExcelRenderer to operate on data from db and render it as sheet. Converted data can be exported to file later.
You can just create array of array (aoa) that follows expected view (rows = array of row cells array). To do this you need very easy algorithm:
let newData = []
map over emplyers, for each (emp):
set flag let first = true;
map over shifts, for each (shift):
if( first ) { newData.push( [emp.name, emp.descr, shift.name, shift.timezone...]); first = false;
} else newData.push( [null, null, shift.name, shift.timezone...]);
setRows( newData );
Rendering
<OutTable/> operates on data and colums props - structures similar to internal state. 'datais ourrows, we only needcolumns` prop, just another state value:
const [columns, setColumns] = useState([
{ name: "Employer name", key: 0 },
{ name: "Employer description", key: 1 },
{ name: "Shift name", key: 2 },
// ...
]);
and finally we can render it
return (
<OutTable data={rows] columns />
Later
User can operate on sheet view - f.e. insert rows using setRows() or download this as file (XLSX.writeFile()) after simple conversion:
var ws = XLSX.utils.aoa_to_sheet( columns.concat( rows ) );
There is a lot of utils you can use for conversions - see samples.
Back to your needs
We have data loaded from db, data in aoa form, rendered as sheet. I don't fully understand format you need, but for your db format conversion is simple (opposite to above) - you can follow it and adjust to your needs.
let newEmployers = [];
let empCounter = -1;
// itarate on rows, on each (`row`):
rows.map( (row) => {
// new employer
if( row[0] ) {
newEmployers.push( {
// id should be here
"employerName": row[0],
"employerDescription": row[1],
"shifts": [
{
"shiftName": row[3],
"shiftDescription": row[4],
// ...
}
]
} );
empCounter ++;
} else {
// new shift for current employer
newEmployers[empCounter].shifts.push(
{
"shiftName": row[3],
"shiftDescription": row[4],
// ...
}
);
}
});
// newEmployers can be sent to backend (as json) to update DB
At the bottom is a slimmed down version of a JSON file that I am trying to parse. I would like to create individual objects that have a key for the team name and the player name.
How would I go about using the team name and mapping to each individual player and receive something like this (using javascript):
[
{ name: 'Dallas Stars', playerName: 'Alexander Radulov'},
{ name: 'Dallas Stars', playerName: 'Ben Bishop'},
{ name: 'Dallas Stars', playerName: 'Jamie Benn'}
...
{ name: 'Columbus Blue Jackets', playerName: 'Pierre-Luc Dubois'}
]
From this JSON:
[ { name: 'Dallas Stars',
roster:
[ 'Alexander Radulov',
'Ben Bishop',
'Jamie Benn',
'Tyler Pitlick',
'Miro Heiskanen' ] },
{ name: 'Los Angeles Kings',
roster:
[ 'Jonathan Quick',
'Jonny Brodzinski',
'Oscar Fantenberg' ] },
{ name: 'San Jose Sharks',
roster:
[ 'Joe Thornton',
'Brent Burns',
'Joe Pavelski',
'Antti Suomela' ] },
{ name: 'Columbus Blue Jackets',
roster:
[ 'Sonny Milano',
'Brandon Dubinsky',
'Nick Foligno',
'Pierre-Luc Dubois' ] } ]
Essentially I am trying to map a top level key pair to individual players. I have tried searching through all lodash functions as well and haven't stumbled upon the correct way to do this.
Is there a way to use a flat map and have the team name used multiple times?
You need to iterate over the outer array items, and then inside of each of those, iterate over the roster too. reduce is usually the most appropriate method for transforming an array into another array on a non-one-to-one basis:
const input=[{name:'Dallas Stars',roster:['Alexander Radulov','Ben Bishop','Jamie Benn','Tyler Pitlick','Miro Heiskanen']},{name:'Los Angeles Kings',roster:['Jonathan Quick','Jonny Brodzinski','Oscar Fantenberg']},{name:'San Jose Sharks',roster:['Joe Thornton','Brent Burns','Joe Pavelski','Antti Suomela']},{name:'Columbus Blue Jackets',roster:['Sonny Milano','Brandon Dubinsky','Nick Foligno','Pierre-Luc Dubois']}];
const output = input.reduce((a, { name, roster }) => {
roster.forEach((playerName) => {
a.push({ name, playerName });
});
return a;
}, []);
console.log(output);
You can also use map and flat.
Map over the original array, then for each item being "mapped" map over its roster and create your desired object. Finally, since the resulting array will be 2d, flatten it:
var data = [{ name: 'Dallas Stars', roster: ['Alexander Radulov', 'Ben Bishop', 'Jamie Benn', 'Tyler Pitlick', 'Miro Heiskanen' ] }, { name: 'Los Angeles Kings', roster: ['Jonathan Quick', 'Jonny Brodzinski', 'Oscar Fantenberg' ] }, { name: 'San Jose Sharks', roster: ['Joe Thornton', 'Brent Burns', 'Joe Pavelski', 'Antti Suomela' ] }, { name: 'Columbus Blue Jackets', roster: ['Sonny Milano', 'Brandon Dubinsky', 'Nick Foligno', 'Pierre-Luc Dubois' ] } ];
var res = data
.map(({name, roster}) =>
roster.map(playerName => ({name, playerName})))
.flat();
console.log(res);
Okay, so I don't know how to properly express my simple problem because of how simple it is, I guess.
Basically, I have an autocomplete done by me in my React project.. I have two inputs "Country" and "City". When I type a country my autocomplete works great giving me suggestions but now I have to make the same for my second input so it would give me a list of cities that depends on which country is typed in the "Country" input...
"United Kingdom" => "London, Birmingham, Bighton etc."
How can I do that? Thank you!
P.S. I already have all the lists of countries and cities, I just don't know how to make the second input to depend on an information in the first one.
Code here
Autocomplete.jsx
https://github.com/lembas-cracker/Weather-app/blob/master/src/Autocomplete.jsx
Form.jsx
https://github.com/lembas-cracker/Weather-app/blob/master/src/Form.jsx
P.S. I already have all the lists of countries and cities, I just don't know how to make the second input to depend on an information in the first one.
If you know which country the city belongs to (perhaps via a key in the city object), you could run a simple filter function to remove any cities that don't belong to that country.
this.state = {
selectedCountry: 'London',
};
const cities = [
{ name: "Toronto", country: "Canada" },
{ name: "London", country: "United Kingdom" }
];
const filteredCities = cities.filter(city => {
return city.country !== this.state.selectedCountry;
});
On your city input field make sure to create an onBlur function to will run the filter on your cities list once the user leaves that input field.
Made a quick example. Did you mean smth like this? Since you haven't provided any part of your source code, I used plain HTML select for the demo.
https://jsfiddle.net/arfeo/n5u2wwjg/204186/
class App extends React.Component {
constructor() {
super();
this.state = {
countryId: 1,
};
}
onCountryChange(countryId) {
this.setState({ countryId: parseInt(countryId) });
}
render() {
return (
<div>
<Input
key="countriesInput"
type="countries"
countryId={this.state.countryId}
onChange={(countryId) => this.onCountryChange(countryId)}
/>
<Input
key="citiesInput"
type="cities"
countryId={this.state.countryId}
/>
</div>
);
}
}
class Input extends React.Component {
constructor() {
super();
this.selectRef = null;
}
renderOptions() {
const countries = [
{
id: 1,
name: 'England',
},
{
id: 2,
name: 'Germany',
},
{
id: 3,
name: 'France',
},
];
const cities = [
{
countryId: 1,
cities: [
{
id: 1,
name: 'London',
},
{
id: 2,
name: 'Liverpool',
},
{
id: 3,
name: 'Salisbury'
}
],
},
{
countryId: 2,
cities: [
{
id: 4,
name: 'Berlin',
},
{
id: 5,
name: 'Frankfurt',
},
],
},
{
countryId: 3,
cities: [
{
id: 6,
name: 'Paris',
},
],
},
];
switch (this.props.type) {
case 'countries': {
return countries.map((country) => (
<option
key={country.id.toString()}
value={country.id}
>
{country.name}
</option>
));
}
case 'cities': {
const citiesMap = cities.filter((city) => city.countryId === this.props.countryId);
if (citiesMap && citiesMap[0]) {
const citiesList = citiesMap[0].cities;
if (citiesList) {
return citiesList.map((city) => (
<option
key={city.id.toString()}
value={city.id}
>
{city.name}
</option>
));
}
}
return null;
}
default: return null;
}
}
render() {
return (
<select name={this.props.type} ref={(ref) => this.selectRef = ref} onChange={() => this.props.onChange(this.selectRef.value)}>
{this.renderOptions()}
</select>
);
}
}
ReactDOM.render(<App />, document.querySelector("#app"))
UPDATE
Make your Form component stateful.
Add a state property for countries in Form (let it be countryId).
Pass this property as a prop into the second Autocomplete component.
When the first Autocomplete changes, change the countryId of the Form.
I've done something similar which may help you.
The Object.keys(instutiontypes) you could use to have an array of countries, instead. Then inside of those values, you can have an array of objects. You could have the cities here, e.g. {value: "Manchester", "label: Manchester", phoneExt: "0114"}
const instutiontypes = {
Kindergarten: [
{ value: "PreK", label: "PreK" },
{ value: "K1", label: "K1" },
{ value: "K2", label: "K2" },
{ value: "K3", label: "K3" },
],
"Primary School": [
{ value: "Grade 1", label: "Grade 1" },
{ value: "Grade 2", label: "Grade 2" },
{ value: "Grade 3", label: "Grade 3" },
{ value: "Grade 4", label: "Grade 4" },
{ value: "Grade 5", label: "Grade 5" },
{ value: "Grade 6", label: "Grade 6" },
],
}
To have the options in my input, I use Object.keys(instutiontypes) to get ['Kindergarten','Primary School']
Then, to get the array of ages to give to my secondary dropdown, I have written this code:
const types = ['Selection1', 'Selection2']
const agesList = [];
for (let i = 0; i < types.length; i++) {
Object.values(institutionTypes[types[i]]).map(({ label }) =>
agesList.push(label)
);
}
This way, the ages dropdown list is dependent on the values passed to institutionTypes.
I'm using mui's <Autocomplete /> components to make them be search dropdowns, with the prop options for the arrays.
I am finding it very difficult to re-define the return information so that it is suitable for ng-repeat to iterate over it in the view.
I have two views one for an index that i want the year-month to encompass the countries (might be 1+ or none) and then inside each country i want the name of each event (again could be 1+ or none). The second view i just want to pass the event details and will be calling these details by passing the event index number in order to return all the event details (name, mname, net).
The Data:
{
months: [
{
index: 201602,
year: "2016",
mon: "February",
country1: [
{
index: 12345678,
l: [
{
name: "Test1",
mname: "Test 1",
net: "February 10, 2016 11:39:00 UTC",
}
]
},
{
index: 23456789,
l: [
{
name: "Test2",
mname: "Test 2",
net: "February 10, 2016 11:39:00 UTC",
}
]
}
],
country2: [ ]
},
{
index: 201603,
year: "2016",
mon: "March",
country1: [
{
index: 546547657654,
l: [
{
name: "Test1",
mname: "Test 1",
net: "March 10, 2016 11:39:00 UTC",
}
]
}
],
country2: []
},
{
index: 201604,
year: "2016",
mon: "April",
country1: [ ],
country2: [
{
index: 78676756,
l: [
{
name: "Test1",
mname: "Test 1",
net: "April10, 2016 11:39:00 UTC",
}
]
}
]
}
]
}
In order for ng-repeat to work, you'll have to extract the country data in some another array (transform the initial data somehow).
If those country fields have consistent naming (like 'country' infix on each of them), you can extract them into their own array and use ng-repeat to iterate over it.
Here is working solution. It assumes that country arrays all have the word 'country' in their name:
function MyCtrl($scope) {
$scope.countriesData = prepData(sampleData);
function prepData(data) {
return data.months.map(function(yearMonth) {
var transformed = { yearMonth: yearMonth, countries: [] };
for (var key in yearMonth) {
if (key.indexOf('country') != -1) {
transformed.countries.push(yearMonth[key]);
}
}
return transformed;
});
}
}
var sampleData = {
months: {
//...
}
}
The solution takes the data you've provided and transforms it into an array of entries like this one: { yearMonth: yearMonth, countries: [] };
You'll just have to render them like this:
<div ng-controller="MyCtrl">
<ul>
<li ng-repeat="entry in countriesData">
ym-id: {{entry.yearMonth.index}}
<ul>
<li ng-repeat="country in entry.countries">
<ul>
<li ng-repeat="event in country">
event-id: {{event.index}}
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
You can check the fiddle here: http://jsfiddle.net/tvy4jbvs/
I am trying to build a 3D Javascript array, but I am unsure of how to do it, basically I have 3 arrays, Provinces, Cities and Malls all in succession, so I want to create a 3D array to store all the data in and then write some jQuery/Javascript to get out what I need.
I have a script that can populate a drop down list with array items, but now I am adding an extra dimension to it and I am getting a little confused as to how to proceed, here is the code I have thus far,
The jQuery:
<script>
model[0] = new Array( 'Arnage', 'Azure', 'Brooklands', 'Continental', 'Corniche', 'Eight', 'Mulsanne', 'Series II', 'Turbo R', 'Turbo RT');
model[1] = new Array( '412', '603', 'Beaufighter', 'Blenheim', 'Brigand', 'Britannia');
model[2] = new Array( 'Inyathi', 'Rhino');
model[3] = new Array( 'Amandla', 'Auto Union', 'Horch');
function makeModel(obj){
var curSel=obj.options[obj.selectedIndex].value ;
var x;
if (curSel != 'null'){
$('#model').css({'display' : 'block'});
$('#model').html("<select name='model' id='sub'>");
for (x in model[curSel])
{
$('#sub').append("<option value='" + model[curSel][x] + "'>" + model[curSel][x] + "</option>");
}
}else{
$('#model').css({'display' : 'block'});
}
}
</script>
The HTML:
<form>
<p>
<span class='left'><label for='make'>Make: </label></span>
<span class='right'><select name='make' id='make' onchange='makeModel(this);'>
<option value='0'>Select one</option>
<option value='1'>one</option>
<option value='2'>two</option>
<option value='3'>three</option>
<option value='4'>four</option>
</select>
</span>
</p>
<p>
<div id='model'></div>
</p>
</form>
So as you can see, the above code generates a drop down menu of models depending on what make I select, now what I want to achieve now is adding one more level to it, so they will click on a province, then the cities drop down will appear, and when they choose a city, the malls will appear.
What would be the best way of approaching this?
Thanx in advance!
If you have a structure like this one
var provinces = [
{ name: "Province A", cities: [
{ name: "City A.A", malls: [
{ name: "Mall A.A.1" },
{ name: "Mall A.A.2" }
] },
{ name: "City A.B", malls: [
{ name: "Mall A.B.1" }
] }
] },
{ name: "Province B", cities: [
{ name: "City B.A", malls: [
{ name: "Mall B.A.1" },
{ name: "Mall B.A.2" }
] },
{ name: "City B.B", malls: [] }
] }
];
Then you can populate the dropdowns like so:
function populateDropdown(drop, items) {
drop.empty();
for(var i = 0; i < items.length; i++) {
drop.append('<option value=' + i + '>' + items[i].name + '</option>');
}
drop.show();
}
populateDropdown( $('#provinces'), provinces );
And upon an action:
$('#provinces').change(function() {
var provinceIndex = $(this).val();
var province = provinces[provinceIndex];
populateDropdown( $('#cities'), province.cities );
$('#malls').hide();
});
$('#cities').change(function() {
var provinceIndex = $('#provinces').val();
var province = provinces[provinceIndex];
var cityIndex = $(this).val();
var city = province.cities[cityIndex];
populateDropdown( $('#malls'), city.malls );
});
EDIT
If the data structure on top looks hard to read, by the way, it's the exact same thing as the following:
var provinces = [];
// populate provinces
provinces.push({ name: "Province A", cities: [] });
provinces.push({ name: "Province B", cities: [] });
// populate cities
provinces[0].cities.push({ name: "City A.A", malls: [] });
provinces[0].cities.push({ name: "City A.B", malls: [] });
provinces[1].cities.push({ name: "City B.A", malls: [] });
provinces[1].cities.push({ name: "City B.B", malls: [] });
// populate malls
provinces[0].cities[0].malls.push({ name: "Mall A.A.1" });
provinces[0].cities[0].malls.push({ name: "Mall A.A.2" });
provinces[0].cities[1].malls.push({ name: "Mall A.B.1" });
provinces[1].cities[0].malls.push({ name: "Mall B.A.1" });
provinces[1].cities[0].malls.push({ name: "Mall B.A.2" });