Push an object from an array into another array javascript - arrays

I am having an issue with pushing an object into an array. I am fetching an array of objects from a local .json file. I am trying to create a function that pushes the given object into an array, so I can use it later on.
This is how I am receiving my object.
{id: 3176, name: "Matthias Ginter", position: "Defender", dateOfBirth: "1994-01-03T00:00:00Z", countryOfBirth: "Germany", …}
countryOfBirth: "Germany"
dateOfBirth: "1994-01-03T00:00:00Z"
id: 3176
name: "Matthias Ginter"
nationality: "Germany"
position: "Defender"
role: "PLAYER"
__proto__: Object
My code in React:
{data.map(
(player) => (
player.position == null ? (player.position = "Coach") : null,
(
<PlayerCard
name={player.name}
position={player.position}
dateOfBirth={player.dateOfBirth}
nationality={player.nationality}
id={player.id}
handleClick={() => selectedPlayers.push(player)}
/>
)
)
)}
and the array I am trying to push into:
let selectedPlayers = [
{
id: 3176,
name: "Matthias Ginter",
position: "Defender",
dateOfBirth: "1994-01-03T00:00:00Z",
countryOfBirth: "Germany",
nationality: "Germany",
role: "PLAYER",
},
{
id: 3176,
name: "Mat Giensien",
position: "Defender",
dateOfBirth: "1994-01-03T00:00:00Z",
countryOfBirth: "Germany",
nationality: "Germany",
role: "PLAYER",
},
];
if I do handleClick = {() => {console.log(player)}} I get the object as shown above. What am I missing ?!
I read through all the topics here in SO but couldn't find a solution that would work for me. I have tried all the reccomended ways in the other topics and they still don't work for me.
Please, halp meeeeh :)

{data.map(player => {
return (
<PlayerCard
name={player.name}
position={player.position ? "Coach" : null}
dateOfBirth={player.dateOfBirth}
nationality={player.nationality}
id={player.id}
handleClick={() => selectedPlayers.push(player)}
/>
)
)}

Try this:
let selectedPlayers = [
{
id: 3176,
name: "Matthias Ginter",
position: "Defender",
dateOfBirth: "1994-01-03T00:00:00Z",
countryOfBirth: "Germany",
nationality: "Germany",
role: "PLAYER"
},
{
id: 3176,
name: "Mat Giensien",
position: "Defender",
dateOfBirth: "1994-01-03T00:00:00Z",
countryOfBirth: "Germany",
nationality: "Germany",
role: "PLAYER"
}
];
let newData = {id: 9999, name: "bob jones", position: "goalkepper", dateOfBirth: "2020-01-03T00:00:00Z", nationality: "Spain", role: "MANAGER"}
selectedPlayers.push(newData);
console.log( selectedPlayers );
You might have to mess around with the formatting of the recevied object and the object you're pushing into to make iy work properly. But, if you're in control of the code and the JSON file then that shouldn't be an issue...

Related

How to generate ID's on my existing data array with 20 id's/users on JavaScript/React

This is my data.js. I want to increment the last existing data to plus 1 if I add another user to my table. I used nanoid from my previous generating ids to my userRows data. But I want my id to increment by 1. For example, the last user that I created has an ID of 20 and I want my next user would be 21. Can someone help me or guide me to fix my generating ids? Thank you in advance.
export const userRows = [
{
id: 1,
username: "Richmond",
fullName: "Richmond Vicente Ramil",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-template/demo-1/images/avatars/3.png",
status: "active",
email: "Richmond#gmail.com",
age: 22,
},
{
id: 2,
username: "Fernand",
fullName: "Fernaan Million Galeron",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-template/demo-1/images/avatars/3.png",
status: "passive",
email: "Fernand#gmail.com",
age: 23,
},
{
id: 3,
username: "Jerson",
fullName: "Jerson Tablatin Aganon",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-template/demo-1/images/avatars/3.png",
status: "active",
email: "Jerson#gmail.com",
age: 23,
},
{
id: 4,
username: "Jyvonn",
fullName: "Jyvonn Nool Juan",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-template/demo-1/images/avatars/3.png",
status: "active",
email: "Jyvonn#gmail.com",
age: 24,
},
{
id: 5,
username: "Mike",
fullName: "Mike Tyson Kid",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-template/demo-1/images/avatars/3.png",
status: "pending",
email: "Mike#gmail.com",
age: 20,
},
{
id: 6,
username: "Mark",
fullName: "Mark Bryant Cleofas",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-template/demo-1/images/avatars/3.png",
status: "passive",
email: "Mark#gmail.com",
age: 26,
},
{
id: 7,
username: "Bryan",
fullName: "Bryan Brenna Tiofelo",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-template/demo-1/images/avatars/3.png",
status: "active",
email: "Bryan#gmail.com",
age: 32,
},
{
id: 8,
username: "Jonathan",
fullName: "Jonathan Nool Cleofas",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-template/demo-1/images/avatars/3.png",
status: "active",
email: "Jonathan#gmail.com",
age: 19,
},
{
id: 9,
username: "Walter",
fullName: "Walter Mike Mart",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-template/demo-1/images/avatars/3.png",
status: "pending",
email: "Walter#gmail.com",
age: 30,
},
{
id: 10,
username: "Vincent",
fullName: "Vincent Abdul Saudi",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-template/demo-1/images/avatars/3.png",
status: "pending",
email: "Vicent#gmail.com",
age: 42,
},
{
id: 11,
username: "Galeon",
fullName: "Galeon Mark Apollo",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-template/demo-1/images/avatars/3.png",
status: "active",
email: "Galeon#gmail.com",
age: 46,
},
{
id: 12,
username: "Brandon",
fullName: "Brandon Vicente Ramil",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-template/demo-1/images/avatars/3.png",
status: "passive",
email: "Brandon#gmail.com",
age: 25,
},
{
id: 13,
username: "Kenneth",
fullName: "Kenneth Timothy Sison",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-template/demo-1/images/avatars/3.png",
status: "passive",
email: "Keneth#gmail.com",
age: 26,
},
{
id: 14,
username: "Alexis",
fullName: "Alexis Delos Santos",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-template/demo-1/images/avatars/3.png",
status: "active",
email: "Alexis#gmail.com",
age: 22,
},
{
id: 15,
username: "John",
fullName: "John Kyle Abrera",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-template/demo-1/images/avatars/3.png",
status: "active",
email: "John#gmail.com",
age: 28,
},
{
id: 16,
username: "Patrick",
fullName: "Patrick Martin Nievera",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-template/demo-1/images/avatars/3.png",
status: "pending",
email: "Patrick#gmail.com",
age: 23,
},
{
id: 17,
username: "Steve",
fullName: "Steve Work Job",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-template/demo-1/images/avatars/3.png",
status: "active",
email: "Steve#gmail.com",
age: 24,
},
{
id: 18,
username: "Ralph",
fullName: "Ralph Dela Pena",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-template/demo-1/images/avatars/3.png",
status: "passive",
email: "Ralph#gmail.com",
age: 46,
},
{
id: 19,
username: "Chandler",
fullName: "Chandler Dark Mosquito",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-template/demo-1/images/avatars/3.png",
status: "active",
email: "Chandler#gmail.com",
age: 29,
},
{
id: 20,
username: "Reyster",
fullName: "Reyster John Car",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-template/demo-1/images/avatars/3.png",
status: "active",
email: "Reyster#gmail.com",
age: 29,
},
];
I want to generate ID. if I add a new user, the next id will be 21
const newUser = {
//I want to put the next id which is 21 here on my newUser object and id property
//id: ID 21 here ,
username: addFormData.username,
img: file
? URL.createObjectURL(file)
: "https://yt3.ggpht.com/CblhnSj8-Q6Ptr6n8Nq1e3wB4gadeNM_IYjDma89iNfuTrAfsMwogvkPFb6JbG8XS-fdBnN5Plk=s88-c-k-c0x00ffffff-no-rj-mo",
fullName: addFormData.fullName,
email: addFormData.email,
age: addFormData.age,
status: addFormData.status,
};
You can create a function that will receive the last user id and return incremented value, something like that:
function generateNewUserId(users) {
return users[users.length - 1].id + 1;
}
console.log(generateNewUserId(userRows)); // -> "21" for your array
If your data is stored on the backend, you can generate the ID there.
By the way, the first option that could come to mind when implementing this, is to use array.length, but this could create a mess, if you gonna have DELETE user functionality.
What you can do is, use a generator function:
function* generateId() {
let count = 0;
while (true) {
yield ++count;
}
}
const iterator = generateId();
const incrementalId = () => {
const { value } = iterator.next();
if (value) return value;
return -1;
};
Now use the incrementalId function to generate incremental Ids:
export const userRows = [
{
id: incrementalId(), // 1
username: "Richmond",
fullName: "Richmond Vicente Ramil",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-
template/demo-1/images/avatars/3.png",
status: "active",
email: "Richmond#gmail.com",
age: 22,
},
{
id: incrementalId(), // 2
username: "Fernand",
fullName: "Fernaan Million Galeron",
img: "https://demos.themeselection.com/materio-mui-react-nextjs-admin-
template/demo-1/images/avatars/3.png",
status: "passive",
email: "Fernand#gmail.com",
age: 23,
},
// so on...
];
const newUser = {
id: incrementalId(), // 21 (after invoking incrementalId for 20 times)
username: addFormData.username,
img: file
? URL.createObjectURL(file)
: "https://yt3.ggpht.com/CblhnSj8-
Q6Ptr6n8Nq1e3wB4gadeNM_IYjDma89iNfuTrAfsMwogvkPFb6JbG8XS-fdBnN5Plk=s88-
c-k-c0x00ffffff-no-rj-mo",
fullName: addFormData.fullName,
email: addFormData.email,
age: addFormData.age,
status: addFormData.status,
};

Is there a way to group columns in MUI-dataTable?

I am using MUIDataTable in my React project. I just want to group columns by adding borders to the table. Please find the code below which I am using.
const columns = [
{
name: "name",
label: "Name",
options: {
filter: true,
sort: true,
[customBodyRender: (value) => {
return (
<div style={{ borderRight: "solid 2px" }} >
{value}
</div>
)
}][1]
}
},
{
name: "company",
label: "Company",
options: {
filter: true,
sort: false,
}
},
{
name: "city",
label: "City",
options: {
filter: true,
sort: false,
customBodyRender: (value) => {
return (
<div style={{ borderRight: "solid 2px" }} >
{value}
</div>
)
}
}
},
{
name: "state",
label: "State",
options: {
filter: true,
sort: false,
}
},
];
const data = [
{ name: "Joe James", company: "Test Corp", city: "Yonkers", state: "NY" },
{ name: "John Walsh", company: "Test Corp", city: "Hartford", state: "CT" },
{ name: "Bob Herm", company: "Test Corp", city: "Tampa", state: "FL" },
{ name: "James Houston", company: "Test Corp", city: "Dallas", state: "TX" },
{ name: "", company: "", city: "Tampa", state: "" },
{ name: "", company: "", city: "", state: "" },
{ name: "", company: "", city: "Hartford", state: "" },
{ name: "", company: "", city: "", state: "" },
{ name: "", company: "", city: "", state: "" },
{ name: "", company: "", city: "", state: "" },
];
const options = {
filterType: 'checkbox',
};
<MUIDataTable
title={"Employee List"}
data={data}
columns={columns}
options={options}
/>
This is not working as expected. Either the border height is not proper or in case of no data in the table row, there is no border at all.
I also want the borders to appear on the table headers.
I have attached the snapshot of the output for reference.
OutputImage
Is there a way to fix this?
there is a PR but it's in beta only https://github.com/gregnb/mui-datatables/pull/1441, not yet merged into the master branch

ReactJS: update record of an object of an array within an array

I am learning reactJS, I was doing a practice example where I have to update a product and it’s quantity. The final output is required in the following form:
productData = [
name: '',
code: '',
Quantity: [specificationName: "", quantity: ""]
]
I have added functionality for adding record in productData. But I am facing problem in updating Quantity array. Instead of updating data, a new record is added in Quantity array. I am not using index because I have read that it’s not a good approach when our data is non-static.
Below is my code:
handleSubmit = (event) => {
let productData = {};
let specificationQuantity = [];
const productForm = new FormData(event.target);
for (var [key, value] of productForm.entries()) {
if (key !== "name" && key !== "code" ){
let updateQuantity = {
specificationName: key,
quantity: value
}
specificationQuantity.push(updateQuantity)
}
productData = {
name: colorForm.get('name'),
code: colorForm.get('code'),
Quantity: specificationQuantity
}
}
this.state.productData.push(productData)
}
Let's say, I have the following 2 record after addition
{
code: "#0000C3",
name: "Blue",
Quantity: Array(2)
0: {name: "", quantity: ""} // this record is automatically created idk why
1: {name: "v1", quantity: "1"}
}
{
code: "#00001E",
name: "Black",
Quantity: Array(2)
0: {name: "", quantity: ""}
1: {name: "v2", quantity: "2"}
}
and when I try to update the quantity of “v1” to 3 then only that quantity which is in Blue should be updated like {name: ‘v1’, quantity: ‘3’}
but I am getting the following result
{
code: "#0000C3",
name: "Blue",
Quantity: Array(3)
0: {name: "", quantity: ""} // this record is automatically created idk why
1: {name: "v1", quantity: "1"}
2: {name: "v1", quantity: "3"}
}
{
code: "#00001E",
name: "Black",
Quantity: Array(3)
0: {name: "", quantity: ""}
1: {name: "v2", quantity: "2"}
2: {name: "v1", quantity: "3"}
}
The problem lies in this line
this.state.productData.push(productData)
You are actually mutating the state directly which is why you are facing unexpected behaviour.
Please have a look at this:
https://reactjs.org/docs/state-and-lifecycle.html#using-state-correctly

CheckboxGroupInput not rendering after save in react-admin

I'm new to react and react-admin and I have a problem with CheckboxGroupInput or with any input of array type.
I have a form, this is the code:
export const MoviesCreate = (props) => (
<Create {...props}>
<SimpleForm>
<TextInput source="name" validate={[required()]} />
<TextInput source="actors" validate={[required()]} />
<TextInput source="year" validate={[required()]} />
<CheckboxGroupInput source="gender" validate={[required()]} choices={[
{ id: 'Action', name: 'Action' },
{ id: 'Adventure', name: 'Adventure' },
{ id: 'Animation', name: 'Animation' },
{ id: 'Biography', name: 'Biography' },
]} />
</SimpleForm>
</Create>
);
So when I want to create a new item, after I hit the save button I got this error:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
I think the problem is that the response from REST API is not correctly returned but I don't know what is the correct format for that. These are the responses that I tried to returned from REST API but nothing works:
1.
{id: 42, name: "test", year: "1234", actors: "asd", gender: "Adventure,Animation"}
2.
{id: 43, name: "Black Friday", year: "1234", actors: "asd", gender: ["Animation", "Adventure"]}
3.
{id: 43, name: "Black Friday", year: "1234", actors: "asd", gender: [{id: "Adventure", name: "Adventure"}, {id: "Animation", name: "Animation"}]}
4.
{id: 43, name: "Black Friday", year: "1234", actors: "asd", gender: {id: "Animation", name: "Animation"}}
I have the same problem with ArrayInput or AutocompleteArrayInput...
Can anyone help me with this problem and tell me what am I doing wrong?
If you want to let the user choose multiple values among a list of possible values by showing them all,<CheckboxGroupInput> is the right component. Set the choices attribute to determine the options (with id, name tuples):
Description
<CheckboxGroupInput source="category" choices={[
{ id: 'programming', name: 'Programming' },
{ id: 'lifestyle', name: 'Lifestyle' },
{ id: 'photography', name: 'Photography' },
]} />
So,the response from REST API should be like:option 3
{id: 43, name: "Black Friday", year: "1234", actors: "asd", gender: [{id: "Adventure", name: "Adventure"}, {id: "Animation", name: "Animation"}]}

Comparing 2 arrays to create a 3rd array of common items in Angular

I am trying to figure out the TypeScript logic to compare 2 arrays and create a 3rd array of all the common items.
i.e.
employees: any;
offices: any;
constructor() {
this.employees = [
{ fname: "John", lname: "James", state: "New York" },
{ fname: "John", lname: "Booth", state: "Nebraska" },
{ fname: "Steve", lname: "Smith", state: "Nebraska" },
{ fname: "Stephanie", lname: "Smith", state: "New Hampshire" },
{ fname: "Bill", lname: "Kydd", state: "New Mexico" },
{ fname: "Bill", lname: "Cody", state: "Wyoming" }
]
this.offices = [
{ state: "New York", city: "Albany" },
{ state: "Nebraska", city: "Omaha" },
{ state: "New Mexico", city: "Albuquerque" },
{ state: "New Hamshire", city: "Manchester" },
{ state: "California", city: "Redding" }
]
let finalOffice = this.employees.filter((state: any) => !this.offices.include(state));
console.log(finalOffice);
}
Ideally the third array would be something like:
empofclist = [
{state: "New York", city: "Albany", fname: "John",lname: "James"},
{state: "Nebraska", city: "Omaha",fname: "John",lname: "Booth"},
{state: "Nebraska", city: "Omaha",fname: "Steve",lname: "Smith"},
{state: "New Mexico", city: "Albuquerque",fname: "Bill",lname: "Kydd"},
{state: "New Hamshire",city: "Manchester",fname: "Stephanie",lname: "Smith"}
]
Note that there is a duplicate of Nebraska, one for each person, and there is no listing for California as there no employee there and not listing for Bill Cody as there is no office in Wyoming.
Any suggestions on where I can find information on this?
this.employees = [
{ fname: "John", lname: "James", state: "New York" },
{ fname: "John", lname: "Booth", state: "Nebraska" },
{ fname: "Steve", lname: "Smith", state: "Nebraska" },
{ fname: "Stephanie", lname: "Smith", state: "New Hampshire" },
{ fname: "Bill", lname: "Kydd", state: "New Mexico" },
{ fname: "Bill", lname: "Cody", state: "Wyoming" }
];
this.offices = [
{ state: "New York", city: "Albany" },
{ state: "Nebraska", city: "Omaha" },
{ state: "New Mexico", city: "Albuquerque" },
{ state: "New Hampshire", city: "Manchester" },
{ state: "California", city: "Redding" }
]
let finalArr = [];
let self = this;
for (let g=0;g<self.employees.length;g++) {
for (let h=0;h<self.offices.length;h++) {
if (self.employees[g]['state'] === self.offices[h]['state']) {
finalArr.push(self.employees[g]);
finalArr[finalArr.length - 1]['city'] = self.offices[h]['city'];
break;
}
}
}
console.log(finalArr);
You can try something like this.

Resources