I have a login form, which I have implemented using reactive forms. I have created a static table also, once the login form is filled and clicked the save button, all the values will be populated in to that table. I need to implement an edit button in that table. Once the edit button got clicked all the table values should be populated back to the login form. How should I implement this in Angular 13
1. Find the userId that you need to update (create an edid button on each table item which gives you the id).
2. If its an array your can use find Index
3. Now update your array index to the given value.
// Login Table List
let loginList = [
{ userID: 1, userName: 'Alex' },
{ userID: 2, userName: 'Bob' },
{ userID: 3, userName: 'Soni' }
]
// Update function
const update = (userID, userName) => {
let index = loginList.findIndex((userName, index) => userName.userID === userID);
loginList[index] = { userID: userID, userName: userName }
}
update(1, 'George');
console.log(loginList);
/*
// Updated Login List
[
{ userID: 1, userName: 'Geroge' },
{ userID: 2, userName: 'Bob' },
{ userID: 3, userName: 'Soni' }
]
*/
Related
Here I am trying to modify my data over the iteration and send some result to API call.
The API Call receives a request with a structured data format which is
{ list: [{ id: "1", name: "Hello" }, ... ] }
Somehow I managed to call the API with single data ( const params in my current code, it only accepts single data).
But now it has to be done with multiple data something like this:
{ list: [{ id: "1", name: "Hello" }, { id: "22", name: "Ed" }, { id: "36", name: "Jason" } ... ] }
Here is my current code
const [table, setTalbe] = useState(..); // assume, we have some table data here
const processNow = () => {
let id = 0;
let name = '';
// if table length is greater than 1, we go for the loop.
if (table.length >= 1) {
table.map(data => {
id = data.userId;
name = data.userName;
});
//insert table data to params, here I want to add whole table data into "list"
//the final result of this list should be something like this
//ex ) list: [{ id: '123', name: 'Josh' }, { id: '125', name: 'Sue' }, { id: '2222', name: 'Paker' } ...],
// but how??
const params: any = {
list: [
{
id: id,
name: name
},
],
};
//send PUT reqeust with params
axios
.put(
'/api/v1/tosent',
params,
)
.then(res => {
console.log('The response', res);
})
.catch(err => {
console.log('The error: ', err);
});
}
};
but I'm stuck with it, please help me to finish this code to work properly.
need your kind advice.
Array.prototype.map returns a new array with the function you pass applied to every element. You should study the MDN documentation on map to understand its use.
Your current code does nothing with the map return value:
table.map(data => {
id = data.userId;
name = data.userName;
});
You probably assumed .map would mutate the data, as in change it in place. Instead, the whole operation returns a new array.
It looks like you want to do:
const list = table.map(data => {
return {
id: data.userId,
name: data.userName
}
});
This is applying a function to every element in the array that will map each element to a new object, matching your question, with an id and name key. Then it looks like you want to pass the returned value of map (which we named list above) to your call:
const params: any = {
list: list
};
I am going to Push some objects in an array and delete them according to there specific ID.
Now the challenge is that i wants to do the both push and delete using a single toggle button.
this.state = {
array: [{
id: 1,
name: "Abc",
checkBoxState: true
}, ]
}
handleData(label, value, id) {
let obj = JSON.stringify({
id: id,
name: label,
checkBoxState: value
});
let array = this.state.array;
array.push(obj);
console.log(array);
}
Please tell me the method how to make it possible on a single button.
For Example if i press ok button i will fetch the properties and push into an array and if i press again this button it will have to delete the object from array according to the ID.
Edit based on your comments. First check to see if the item exists in the array. If it does, delete it. If it does not add a new item. I don't have time to test but something like this may work.
this.state = {
array: [{
id: 1,
name: "Abc",
checkBoxState: true
}]
}
handleData(label, value, id) {
let array = this.state.array;
let arrayIds = Object.values
for (let item of array) {
if (item.id === id) {
let deletedObj = array.filter(item => item.id === id)
this.setState({
array: deletedObj,
})
return
}
}
let obj = JSON.stringify({
id: id,
name: label,
checkBoxState: value
});
array.push(obj);
this.setState({
array
})
}
}
console.log(this.state.array);
}
I have to send the modified data to an api which has json format as below:
{
"Customer": {
"name": "ABC",
"email": ABC#gmail.com,
"password": ""
},
"access": true,
"time": 2000
}
On save I want to set the respective state to api fields.
save=()=>{
let newCustomer={
access:this.state.access,
time:this.state.time,
name: //How can i set the state values for name,email and
password which is in nested form?
email:
password:
}
return axios.put('api',newCustomer)
.then(response => {
})
}
You can directly declare it like your json format.
let newCustomer={
access:this.state.access,
time:this.state.time,
Customer: {
name: ..., // state name from your nested form
email: ..., // state email from your nested form
password: ..., // state password from your nested form
},
}
save=(Customer)=>{
let newCustomer={
...Customer,
access: this.state.access,
time: this.state.time,
}
return axios.put('api', newCustomer)
.then(response => {
console.log(response);
})
}
Then newCustomer will be like Customer but access and time may be different.
In backend you cann access customer name and email like you are accessing an array
Env: NodeJS service using aws-sdk for interacting with DynamoDb.
Problem: When I set an attribute of an item to an array, it is saved as a string. I expect x: ['1'] but I get x: '1'. I believe this is because I'm incorrectly writing my UpdateExpression/ExpressionAttributeValues.
Situation: I have a table with a field called users. Users is an array of uuids that can be updated. An example of an item in the table:
{ x_name: 'Hello',
owner: '123456',
x_uuid: '1357911',
users: []
}
I want to update the users array with a user uuid. To my update function I pass through:
{ users: ['13245395'] }
The update function (data is { users: ['13245395'] }):
updateX(data, { x_uuid }) {
if (!x_uuid) {
throw new Error('No x_uuid supplied')
}
// new doc client
const docClient = new AWS.DynamoDB.DocumentClient();
var params = {
TableName: this.table,
Key: {
'x_uuid': x_uuid
},
UpdateExpression: "set users = :users",
ExpressionAttributeValues:{
":users": `${data.users}`
},
ReturnValues:"ALL_NEW"
};
return new Promise((resolve, reject) =>
docClient.update(params, (error, x) => {
return error ? reject(error) : resolve(x)
})
)
}
}
The result I get is
{ x_name: 'Hello',
owner: '123456',
x_uuid: '1357911',
users: '13245395'
}
but what I expected was:
{ x_name: 'Hello',
owner: '123456',
x_uuid: '1357911',
users: ['13245395']
}
Previously tried:
wrapping data.users in an array when creating params (works for the first id but the second id added gets appended to the same string as the first so it looks like ['123,456'] instead ['123', '456'].
UpdateExpression: "set users = :users",
ExpressionAttributeValues:{
":users": [${data.users}]
},
Using the "L" and "S" data types to determine that it's an array of strings, i.e.
UpdateExpression: "set users = :users",
ExpressionAttributeValues:{
":users": { "L": { "S":${data.users} } }
},
You are converting your users array to a string
":users": `${data.users}`
Try
":users": data.users
This will set users to the array in data.users
I have a sample response which I received, the structure is something like this:
A = [{ user:
{ score_level: 16,
is_system: false,
location: 'Mumbai',
email: 'abc#xyz.org',
image: 'example.org',
firstname: Steve},
details: { solution_count: 1, average_rating: 1, recommendation_count: 0 },
score: 45},
{ user:
{ score_level: 17,
is_system: false,
location: 'Miami',
email: 'ab.org',
image: 'example.net',
firstname: Mark},
details: { solution_count: 1, average_rating: 1, recommendation_count: 0 },
score: 50}]
We are getting some information about the user, so what I would like to do is to get only the fistname for every user from this file.
I tried using:
var read = JSON.parse(A);
var firstname = read["user"]["firstname"];
But this dosent seem to work, can you suggest a solution for this?
You can map through the array of objects, check if the object is a user object, and if so, return the firstname. This will yield an array of firstname values.
const names = A.map((obj) => {
if (obj.user) {
return obj.user.firstname;
}
});