How to take an input from a form and store a variable in an existing object - javascript-objects

I'm trying to take data from a form and add it to an existing Object movieData. I am able to pass all the lower key value pairs in but the title which is a top layer key is not recognised and is passed as a string. Any ideas how I can do this? Thanks in advance for your help.
let movieData = {
"The Darjeeling Limited": {
plot: "A year after their father's funeral, three brothers travel across India by train in an attempt to bond with each other.",
cast: ["Jason Schwartzman", "Owen Wilson", "Adrien Brody"],
runtime: 151,
rating: 7.2,
year: 2007,
}
...
}
function handleForm(event) {
event.preventDefault();
const newTitle = document.getElementById("newTitle").value;
const newRating = document.getElementById("newRating").value;
const newYear = document.getElementById("newYear").value;
const newRuntime = document.getElementById("newRuntime").value;
const newCast = document.getElementById("newCast").value;
const newPlot = document.getElementById("newPlot").value;
var addNewMovie = {
newTitle : {
rating: newRating,
year: newYear,
runtime: newRuntime,
cast: newCast,
plot: newPlot,
}
};
Object.assign(movieData, addNewMovie)
console.log(movieData);
displayMovieData();
}
form.addEventListener('submit',handleForm);
I've tried this but unfortunately newTitle doesn't register and gets passed as a string.

var addNewMovie = {
[newTitle] : {
rating: newRating,
year: newYear,
runtime: newRuntime,
cast: newCast,
plot: newPlot,
}
};
I realised I needed to add square brackets around the first key/variable.
https://www.geeksforgeeks.org/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal/

Related

React store data from a state into another state

can anyone please help me solve this problem, I am trying to get some attribute from the tempList state to store into listReceiver state by using gosetListReceiver() function below.
const [tempList, setTempList] = useState([]);
const [listReceiver, setListReceiver] = useState([]);
function gosetListReceiver() {
let i = 0;
while (i < tempList.length) {
setListReceiver([
...listReceiver,
{
name: tempList[i]["name"],
phone: tempList[i]["receiver"]
}
]);
i++;
}
}
but when I am mapping/console the listReceiver state after that , I expect that it will store 3 array from the tempList into listReceiver but it only have the last item from tempList that stored into it. how can i fix this?
below the sample data of tempList as i need to take name and receiver attribute to store into listReceiver
Every time through the loop, you are overwriting the state and thus wiping out anything you did on the last time through the loop. To fix this, you have two options.
Use the function version of set state so that you always get passed in the most recent version of the state:
setListReceiver((prev) => [
...prev,
{
name: tempList[i]["name"],
phone: tempList[i]["receiver"],
},
]);
Wait until you've created the full array, and then set state just once at the end:
function gosetListReceiver() {
let i = 0;
const newState = [...listReceiver];
while (i < tempList.length) {
newState.push({
name: tempList[i]["name"],
phone: tempList[i]["receiver"],
});
i++;
}
setListReceiver(newState);
}
P.S, this code looks like it would be better as a for loop, instead of a while loop:
const newState = [...listReceiver];
for (let i = 0; i < tempList.length; i++) {
newState.push({
name: tempList[i]["name"],
phone: tempList[i]["receiver"],
});
}
setListReceiver(newState);
I didn't tested, but the array brackets [] at the beginning of setListReceiver() looks suspicious to me.
Try without them:
...
setListReceiver(
...listReceiver,
{
name: tempList[i]["name"],
phone: tempList[i]["receiver"]
}
);
...
Or a way which should definitelly work, have a look at Array.push(...).

Count the duplicates in a string array using React JS

Following is a code I implemented to create a bar chart using chart js in React app. Here it creates a bar chart with all the data in an array. But, I want to change this code only to give the output in the x-axis - destination, y-axis - no. of occurrence of this destination since it has many repeated destinations.
I searched methods to this but I couldn't get a correct solution.
Can anyone help me to do this?
const dataArrayY4 = [];
res.data.map(item => {
dataArrayY4.push(item.time)
})
const dataArrayX4 = []
res.data.map(item => {
dataArrayX4.push(item.destination)
})
this.setState({
data4: dataArrayY4,
labels4: dataArrayX4,
});
This could be done as follows:
const res = {
data: [
{ time: 1, destination: 'A'},
{ time: 3, destination: 'A'},
{ time: 2, destination: 'B'}
]
};
let tmp4 = [];
res.data.map((o, i) => {
const existing = tmp4.find(e => e.destination == o.destination);
if (existing) {
existing.time += o.time;
} else {
tmp4.push({time: o.time, destination: o.destination});
}
})
this.setState({
data4: tmp.map(o => o.time);
labels4: tmp.map(o => o.destination);
});
Above code could further be optimized by using Array.reduce() instead of Array.map().
I would make the code more efficient. Instead of dataArrayY4 being an array, I would make it an object that has a key of value and the number of occurrence of each value. This way, you can count all the number of occurrences of the all items in res.data
const dataArrayY4 = {};
res.data.map(item => {
dataArrayY4[item.destination] = (dataArrayY4[item.destination] || 0) + 1
})
const dataArrayX4 = []
res.data.forEach(item => {
dataArrayX4.push(item.destination)
})
this.setState({
data4: dataArrayY4,
labels4: dataArrayX4,
});
Then if you want to look for the occurrence of a particular value you
use this eg. Sri Lanka
this.state.data4['Sri Lanka']

Understanding ExtJs Class properties

I try to understand how properties works in ExtJs class.
Refer to below code:
Ext.define('My.sample.Person', {
name: 'Unknown',
food: undefined,
foodList: [],
constructor: function(name) {
if (name) {
this.name = name;
}
},
eat: function(foodType) {
console.log(this.name + " is eating: " + foodType);
this.food = foodType;
this.foodList.push(foodType);
//this.foodList = [foodType]
},
showFood:function() {
console.log(this.name);
console.log(this.food);
},
showFoodList:function() {
console.log(this.name);
console.log(this.foodList);
}
});
var bob = Ext.create('My.sample.Person', 'Bob');
bob.eat("Salad");
bob.showFood();
bob.showFoodList();
console.log(bob)
var alan = Ext.create('My.sample.Person', 'alan');
console.log(alan)
alan.showFood();
alan.showFoodList();
<script src="https://cdnjs.cloudflare.com/ajax/libs/extjs/6.2.0/ext-all.js"></script>
If you check the result of "alan", the food = undefined and foodList = ['salad'] because somehow foodList was assigned to prototype.
Meanwhile, if you do like this, then it will behave normally like it should. Any idea why? What is the concept behind?
Result:

update an object with a new object

i have an array that is been already loaded on to view, i need to update a specific object in array
modified_data(){
this.nativeStorage.getItem("modifiedData").then((data)=>{
console.log("modified_data fun", data);
// console.log(this.dailyDays);
var array = this.dailyDays;
for (var i = 0; i < array.length; i++) {
var element = array[i];
// console.log("in aloop",element.day);
if (element.day === data.day) {
console.log("got same da", element);
this.dailyDays.push({
day: data.day,
month: this.currentDate.getMonth(),
year: this.currentDate.getFullYear(),
price: data.price,
brand: data.selectedBrand,
howManyDay: data.selectedDay,
quantity: data.selectedQuantity
});
} else {
}
}
})
}
By using the above code a new object gets added up at the bottom of the array in html,
The array in the view have a date listed if i find the same date then that date should be updated with the new object
some one help me
From what I understand, the logic should look something like this. It looks for an existing object in the array, if it finds a match, returns the index, if not, returns -1. Based on that, you can perform
modified_data(){
this.nativeStorage.getItem("modifiedData").then((data)=>{
console.log("modified_data fun", data);
// console.log(this.dailyDays);
// var array = this.dailyDays;
let updateItem = this.dailyDays.find(this.findIndexToUpdate, data.day);
let index = this.dailyDays.indexOf(updateItem);
if(index > -1){
// Add whatever logic you need to update existing object
// below line will replace the whole object
this.dailyDays[index] = data;
}
else{
this.dailyDays.push({
day: data.day,
month: this.currentDate.getMonth(),
year: this.currentDate.getFullYear(),
price: data.price,
brand: data.selectedBrand,
howManyDay: data.selectedDay,
quantity: data.selectedQuantity
})
}
})
findIndexToUpdate(data) {
return data.day === this;
}

Possibility of passing propertie's names as arguments when constructing them

I'm new to Javascript and need to build a function that produces arrays with objects inside to serve data to charts in react.
I want to pass the properties name as a string through an argument to that function. How does this work? I tried out a lot and cannot find an answer online. Sorry for this silly question.
See a simple example code below:
var datakeyelement = "Existing Volume";
var datakeyxaxis = "name";
var datax1 = "Business Clients";
var datae1 = 45;
var datax2 = "Private Clients";
var datae2 = 35;
function chartDataGenerator(
datakeyxaxis,
datakeyelement,
datax1,
datae1,
datax2,
datae2
) {
data = [
{
datakeyxaxis: datax1,
datakeyelement: datae1
},
{
datakeyxaxis: datax2,
datakeyelement: datae2
}
];
return console.log(data);
}
chartDataGenerator(
datakeyxaxis,
datakeyelement,
datax1,
datae1,
datax2,
datae2
);
So the built array with the two object shouldlook like :
[
{
name: Business Clients,
Existing Volume: 45
},
{
name: Private Clients,
Existing Volume: 35
}
]
Basically the only issue I see here is that you need computed prop names
function chartDataGenerator(
datakeyxaxis,
datakeyelement,
datax1,
datae1,
datax2,
datae2
) {
data = [
{
[datakeyxaxis]: datax1,
[datakeyelement]: datae1
},
{
[datakeyxaxis]: datax2,
[datakeyelement]: datae2
}
];
return console.log(data);
}

Resources