Replacing key value in array of objects - javascript

I'm working on a project that is a basic message app. basically i have created an array of objects that allows me to see pre built messages. Then i should be able to click a clear all button and clear all of the messages that are being displayed by looping through the array of objects. this is what i have so far in my messageData.js
const messages = [
{
id: 'message1',
message: 'Hello everyone! Welcome to hell',
userId: 'user1',
},
{
id: 'message2',
message: 'Yall are weirdos!',
userId: 'user3',
},
{
id: 'message3',
message: 'Hey! I think everyone is awesome!',
userId: 'user2',
},
{
id: 'message4',
message: 'Thanks for saying that my friend.',
userId: 'user4',
},
{
id: 'message5',
message: 'Hey buddy, what is up?',
userId: 'user4',
},
];
const getMessages = () => messages;
and what i want to do is basically on click allow the messages key value to be changed to an empty string onclick so that i get rid of the displayed messages without getting rid of the object so that i can later push new messages into these key values.
I started to write this but i seem to be missing something..
const clearBtnFunction = () => {
messages.splice(1, '');
};
i'll be calling the event listener on my main.js file so i'm not super worried about that part yet. I just want to know the proper syntax for replacing the key value in the array if thats possible.

Here is what i opted for. I placed this function, not in the messagesData.js but in the messages.js where i'm building the domstring
const clearBtnFunction = (e) => {
e.preventDefault();
const messages = message.getMessages();
messages.splice(0, messages.length);
messageBuilder(messages);
};

const clearBtnFunction = () => {
messages.foreach( ( message ) => {
message.message = "";
});
};
or with a for loop
const clearBtnFunction = () => {
for( let i =0; i < messages.length; i++) {
messages[i].message = "";
}
};

Related

How to handle the JSON object which lack of some information?

I am using React with nextJS to do web developer,I want to render a list on my web page, the list information comes from the server(I use axios get function to get the information). However some JSON objects are lack of some information like the name, address and so on. My solution is to use a If- else to handle different kind of JSON object. Here is my code:
getPatientList(currentPage).then((res: any) => {
console.log("Response in ini: " , res);
//console.log(res[0].resource.name[0].given[0]);
const data: any = [];
res.map((patient: any) => {
if ("name" in patient.resource) {
let info = {
id: patient.resource.id,
//name:"test",
name: patient.resource.name[0].given[0],
birthDate: patient.resource.birthDate,
gender: patient.resource.gender,
};
data.push(info);
} else {
let info = {
id: patient.resource.id,
name: "Unknow",
//name: patient.resource.name[0].given[0],
birthDate: patient.resource.birthDate,
gender: patient.resource.gender,
};
data.push(info);
}
});
Is there any more clever of efficient way to solve this problem? I am new to TS and React
Use the conditional operator instead to alternate between the possible names. You should also return directly from the .map callback instead of pushing to an outside variable.
getPatientList(currentPage).then((res) => {
const mapped = res.map(({ resource }) => ({
id: resource.id,
// want to correct the spelling below?
name: "name" in resource ? resource.name[0].given[0] : "Unknow",
birthDate: resource.birthDate,
gender: resource.gender,
}));
// do other stuff with mapped
})

How to add a Promise .then() to an Array.push?

I have an array however, one of the object children needs to get data from another location in my Firebase Database to show in the array. This requires a Promise.
How do I show the data from the Promise in the array?
getListofReferrers() {
//
//
// Getting list of referrers from Firebase.
this.eventData.getReferrersList().on('value', snapshot => {
let rawList98 = [];
snapshot.forEach(snap => {
// Bringing the information over into a local array to show on the page.
rawList98.unshift({
id: snap.key,
text: this.eventData.getOtherNameExternal(snap.val().userid).then( (v)=> {return v}),
userid: snap.val().userid,
username: snap.val().username,
email: snap.val().useremail,
referralPoints: this.eventData.numberWithCommas(this.eventData.getOtherProfileProperty(snap.val().userid, "referralPoints") || 0),
});
})
// Taking the information into a "this." variable
this.referralList = rawList98;
console.log(this.referralList);
});
}
I keep getting: [object Promise] when showing the "username" value.
In console.log(rawList98); however, I get the following:
email: "pjoc#pjaguar.com"
id: "referrer9OxMTyUDfiXrLp9O65XW0hUbHgH2"
referralPoints: "0"
username: t
__zone_symbol__state: true
__zone_symbol__value: "John Doe"
[[Prototype]]: Object
userid: "9OxMTyUDfiXrLp9O65XW0hUbHgH2"
How come it's showing the value received from the Promise but I can't capture that in the .then() to properly assign to the child "username"? I will need to call this Promise getting the username for every node in the Firebase Database
Since you need to wait for the username to be available before you can construct the object, you need to put the code inside the .then:
this.eventData.getUserName(snap.val().userid).then(v => {
rawList98.unshift({
id: snap.key,
username: v,
userid: snap.val().userid,
email: snap.val().useremail
});
})
Or, using async/await:
async function someFunction () {
const v = await this.eventData.getUserName(snap.val().userid);
rawList98.unshift({
id: snap.key,
username: v,
userid: snap.val().userid,
email: snap.val().useremail
});
}
The username property that you're pushing into the array is a promise. So to get the actual value in there, you need to use then or await:
const user = rawList98.shift();
const username = await user.username;
console.log(username);
Thanks to Frank van Puffelen. Here was the solution to my issue: I had to put the unshift() in a variable to get the index and use that to assign the username child afterward. I use rawList98.length-user since the unshift function is adding data to the bottom, not the top.
getListofReferrers() {
// Getting list of referrers from Firebase.
this.eventData.getReferrersList().on('value', snapshot => {
let rawList98 = [];
snapshot.forEach(snap => {
var user
user = rawList98.unshift({
id: snap.key,
username: null,
userid: snap.val().userid,
email: snap.val().useremail,
referralPoints: this.eventData.numberWithCommas(this.eventData.getOtherProfileProperty(snap.val().userid, "referralPoints") || 0),
});
this.eventData.getOtherNameExternal(snap.val().userid).then( (v)=> { rawList98[rawList98.length-user].username = v})
})
// Taking the information into a "this." variable
this.referralList = rawList98;
console.log(this.referralList);
});
}

Unable to read object property in Javascript

I'm trying to render a page with some details I get from a api call.
useEffect(() =>{
getCards();
}, [])
const [userCards, setCards] = useState([])
const getCards = async (event) => {
let token = localStorage.getItem("user");
await api
.get("/fetch-card-balance",
{headers:{"token":`${token}`}})
.then((response) => {
console.log(response);
if (response.data.success === false) {
toast.error(response.data.message);
setCards(false);
} else if (response.data.success === true) {
console.log(response.data.payload)
setCards(response.data.payload)
}
})
.catch((err) => {
toast.error(err.response.data.message);
});
};
console.log(userCards)
Here userCards is logged as
[
{
balance: 0.00,
cifNumber: "0001111222",
createdAt: "2021-08-03T12:19:51.000Z",
first6: "123456",
id: 1234,
last4: "7890"
},
{
balance: 20.00,
cifNumber: "0002222333",
createdAt: "2021-07-03T12:19:51.000Z",
first6: "234567",
id: 2345,
last4: "8901"
}
]
Then I try to use forEach to filter the properties I need
const cardDetails = []
userCards.forEach(option => cardDetails.push(
{
cardNumber: `${option.first6}******${option.last4}`,
balance: `${option.balance}`
}
))
But when I run
console.log(cardDetails[0].balance)
I get "Uncaught TypeError: Cannot read property 'balance' of undefined". I've gone over it several times and the only conclusion I have is that I'm missing something that may not be so obvious. Could someone help point out what it is.
Using cardDetails[0].balance will only work when there is at least one element in cardDetails. Otherwise getting the first element in the array yields undefined, causing your error message. Since you only fill the array after the API request returns, at least your first render will be done with an empty array.
An easy way to handle this would be checking for if (cardDetails.length > 0) first.
Try this out
const cardDetails = userCards.map(function(option) { return {cardNumber: ${option.first6}******${option.last4}, balance: ${option.balance}}});

Adding object when nested in Javascript with ES6

I am trying to add an object, but it seems like it is overwriting instead of being added.
I have an initial object:
const config = {
person: 'Bob',
employer: 'yahoo',
}
I'm making a new object elsewhere like so:
const newConfig = {
...config,
customText: { [myVar]: messageText },
[myVar]: selectedItem,
};
myVar can be either message or note that gets sent to Bob.
First, you write a message to Bob, so newConfig looks like this:
const config = {
person: 'Bob',
employer: 'yahoo',
customText: { message: 'hi bob!' }
}
But then later I add a note, and I want the result to be:
const config = {
person: 'Bob',
employer: 'yahoo',
customText: { message: 'hi bob!', note: 'please leave a message for Bob' }
}
Instead, it seems like my object is being overwritten.
const config = {
person: 'Bob',
employer: 'yahoo',
customText: { note: 'please leave a message for Bob' }
}
I've tried to use Object.assign, but I end up in a similar conundrum.
const customText = Object.assign({}, newConfig.customText, {[myVar]: messageText});
I've also tried doing something with the object assignation:
const newConfig = {
...config,
customText[myVar]: messageText,
[myVar]: selectedItem,
};
But I'm getting an Parsing error: Unexpected token, expected ","
How can I add the object without overwriting it?
You need to spread customText too, else it replaces the customText with new property everytime
const newConfig = {
...config,
customText: {...config.customText, [myVar]: messageText },
[myVar]: selectedItem,
};

How to display new Window with specific values from array

I am writing program that is going to help me at work. This part of code is responsible for showing new window with ticket id when there is a "YES" in Warn Owner. Code works fine, yet it only shows first ID from array "found". How I can make it display all stuff?
I Tried this one with .filter yet I was unable to make it work.
if(!isInited) {
ownerNotifyBaseArray = data.map((value) => ({
id: value[dataTicketID],
owner: value[dataWarnOwner],
company: value[dataCompanyName]
}));
} else {
const newOwnerNotifyBaseArray = data.map((value) => ({
id: value[dataTicketID],
owner: value[dataWarnOwner],
company: value[dataCompanyName]
}));
const differences =
_.differenceWith(newOwnerNotifyBaseArray,ownerNotifyBaseArray,_.isEqual)
console.log('differences', differences)
var found = differences.find(z => z.owner === 'Yes');
if(found) {
newWindow = window.open("", "WarnOwner", "width=600,height=200");
newWindow.document.write('<p>Hey! You have a new warn owner on: <b>'+
(found.id)+'</b> for '+(found.company)+'</p>');
newWindow.focus()
//})
ownerNotifyBaseArray = newOwnerNotifyBaseArray
}
ownerNotifyBaseArray = newOwnerNotifyBaseArray
}
New window should contain all entries in array found

Categories