How to setState the object of the object of state - reactjs

Goal: I have two square and I want to change selected square's location. While I'm doing it, I need to change selected square's x-coordinate, y-coordinate, width, and height.
Here is my state which holds the data for square information.
state = {
gestureState: {},
thumbSize: 100,
left: width(100) / 2,
top: height(100) / 2,
taggedClothes: {
0: {id:0, left:100, top:100, thumbSize:100}, <- I want to setState this
1: {id:1, left:200, top:200, thumbSize:200},
},
selectedClothId : 0,
}
Problem: taggedClothes have two square information and I want to change only selected problem but I'm getting compile error
Here I'm performing setState its taggedClothes[0]
// this.state.selectedColorId = 0
var deep = _.cloneDeep(this.state.taggedClothes[this.state.selectedColorId]);
deep.left = left
deep.top = top
deep.thumbSize = thumbSize
this.setState({
gestureState: {
...gestureState
},
taggedClothes[0]: deep <- Getting Compile Error
})
If your have any other suggestion, Please suggest other option!

The key taggedClothes[0] is not valid. You need to spread the taggedClothes and only replace the one that changed:
var deep = _.cloneDeep(this.state.taggedClothes[this.state.selectedColorId]);
deep.left = left
deep.top = top
deep.thumbSize = thumbSize
this.setState({
gestureState: {
...gestureState
},
taggedClothes: {
...taggedClothes,
[this.state.selectedColorId]: deep
}
})

You are trying to access your taggedClothes object like an array.
change this:
taggedClothes: {
0: {id:0, left:100, top:100, thumbSize:100}, <- I want to setState this
1: {id:1, left:200, top:200, thumbSize:200},
},
to that:
taggedClothes: [
{id:0, left:100, top:100, thumbSize:100},
{id:1, left:200, top:200, thumbSize:200},
],
now you should be able to access taggedClothes.

Related

How to return objects that have matching value when comparing to a separate array

In my state I have an object called foodLog which holds all entries a user enters with one of the keys being foodSelectedKey and I'm trying to return all entries that have a matching value from that key with a different array called foodFilter.
However, this doesn't work and errors out saying foodLog.filter() isn't a function - I've looked this up and it's because it's an Object (I think). Any help would be greatly appreciated!
state = {
// log food is for the logged entries
foodLog: {},
// used for when filtering food entries
foodFilter: [],
};
findMatches = () => {
let foodLog = this.state.foodLog;
let foodFilter = this.state.foodFilter;
let matched = foodLog.filter((item) => {
return foodLog.foodsSelectedKey.map((food) => {
return foodFilter.includes(food);
});
});
};
I guess the reason behind the error Is not a function is that the object can not be looped. By that it means you can not iterate an object with differend variables inside, if it has no index to be iterated like an array. The same goes for map(), find() and similar functions which MUST be run with arrays - not objects.
As far as I understand you have an object named foodLog which has an array named foodsSelectedKey. We need to find intersected elements out of foodFilter with the array. This is what I came up with:
state = {
// log food is for the logged entries
foodLog: {
foodsSelectedKey: [
{ id: 1, name: "chicken" },
{ id: 2, name: "mashroom" }
]
},
// used for when filtering food entries
foodFilter: [
{ id: 1, name: "chicken" },
{ id: 2, name: "orange" }
]
};
findMatches = () => {
let foodLog = this.state.foodLog;
let foodFilter = this.state.foodFilter;
let matched = foodLog.foodsSelectedKey.filter((key) =>
{
for (let i=0; i<foodFilter.length;i++){
if(foodFilter[i].name===key.name)
return true
}
return false;
}
);
return matched;
};
The Output is filtered array, in this case, of one element only:
[{
id: 1
name: "chicken"
}]
In order to check the output - run console.log(findMatches()). Here is the CodeSandbox of the solution. (check console at right bottom)

Adding property in array. Add the last value in all array

"I'm adding a property on array while in a forEach loop. But when I do the console.log() the added value on each array is always the last value of the foreach loop."
deliveries data has location and I want to pass the location to pickupDetails.
deliveries: [{ //data of deliveries that I want to pass in pickupDetails
0: {Location: Korea},
1: {Location: Japan}
}]
let pickupDetails = this.state.pickupDetails;
//pickupDetails is only one object then It will become two since the deliveries has 2 objects
pickupDetails = {
name: "June"
}
this.state.deliveries.forEach((delivery, index) => {
pickupDetails.location = delivery.location;
console.log(pickupDetails)
})
the result of the console:
pickupDetails = {
name: "June"
location: "Japan" //this should be Korea since the first loop data is korea
}
pickupDetails = {
name: "June"
index: "Japan"
}
I think something missing from that code maybe because its dummy data. alright from my point of view you confused with javascript reference.
deliveries: [{ //data of deliveries that I want to pass in pickupDetails
0: {Location: Korea},
1: {Location: Japan}
}]
let pickupDetails = this.state.pickupDetails;
this.state.deliveries.forEach((delivery, index) => {
let newPickupDetails = JSON.parse(JSON.stringify(pickupDetails));
newPickupDetails.location = delivery.location;
console.log(newPickupDetails);
})
the result of the console:
pickupDetails = {
name: "Juan"
location: "Japan" //this should be Korea since the first loop data is korea
}
pickupDetails = {
name: "June"
index: "Japan"
}
JSON.parse and JSON.stringify we use for create new object instead of use reference. console log effected because it linked by reference so if you make it new object it will do.
Check variable newPickupDetails

How to access array element correctly from JSON in Angular 5 app?

I have the following JSON definition:
export class Company {
name: string;
trips : Trip[] = [];
}
I am able to see the trips in the console using:
console.log(this.company);
But I am not able to access the array elements (trip), I've tried
the following:
for(let i = 0; i < this.company.trips.length; i++){
console.log(this.company.trips[i]);
}
When I display the company to the log I'm getting the trip as you can
see below:
{id: 1}
name: "Sample"
trips: {id: 1, r: "ABC"}
id: 1
Any idea how to access array elements in Angular thanks?
Using a combination of Object.keys() and forEach() will let you iterate through the the object in a similar fashion to an array.
explination
const x = {hello: "hi"};
console.log(Object.keys(x)); // will return array looking like
// [hello] which you can run a for each on.
Object.keys(x).forEach(data => {
console.log(x[data]); // will return `hi`
});
Solution
const trips = {id: 1, r: "ABC"}; // const trips = this.company.trips
if (trips) // check the value exists here
{
Object.keys(trips).forEach((data) => {
console.log(trips[data]);
});
}
if(this.company)
this.Company.trips.forEach(x => {
console.log(x);
});

How to update object at specific index in array within React state?

I'm building a calorie counting application using React. One of my components has in its state a list of food items:
this.state = {
items: [
{
name: 'Chicken',
selectedServing: {
label: 'breast, grilled',
quantity: 3
}
},
{
name: 'French Fries',
selectedServing: {
label: 'medium container',
quantity: 1
}
}
]
When a user changes the serving size they consumed, I have to update the properties of the item in the items[] array. For example, if a user ate another chicken breast, I'd need to change the selectedServing object in items[0].
Since this array is part of the component's state, I'm using immutability-helper. I've found that I can properly clone and mutate the state in this way:
let newState = update(this.state, {
items: {
0: {
selectedServing: {
servingSize: {$set: newServingSize}
}
}
}
});
The above code sets the servingSize for the first element in the items[] array, which is Chicken. However, I won't know the index of the object I need to update beforehand, so the 0 I hardcoded won't work. It seems that I can't store this index in a variable, because update() will think it's an object key.
How can I programmatically update an object at a specific index in a list?
An variable can be used as a key of an object.
let foo = 3
let newState = { items: { [foo]: { somthing: 'newValue' } } }
// above is equal to { items: { '3': { somthing: 'newValue' } } }
You can find the index number of 'Chicken' and save it into an variable, and use it to composit newState.

Angular: How to update an array object key value dynamically?

I am trying to change the points of selected object that in the exp below.
$scope.players = [{
name: 'Kobe',
points: 10,
asists: 0,
rebounds: 0
}, {
name: 'Jordan',
points: 20,
asists: 0,
rebounds: 0
}, {
name: 'Grant',
points: 30,
asists: 0,
rebounds: 0
},
];
and I assign an object selected with its name.
if($scope.playerName == $scope.players[i].name){
$scope.selectedPlayerPoints = $scope.players[i].points;
$scope.selectedPlayerAsists = $scope.players[i].asists;
$scope.selectedPlayerRebounds = $scope.players[i].rebounds;
}
but I can't update them:
$scope.selectedPlayerPoints.push(playerPoints);
To make it more clear please check: http://plnkr.co/edit/B8Nydni586Se79fDpjnq?p=preview
How it works:
1-click on a player
2-click on points = each time 2 points will be added.
3-as you add more point, it will change the object dynamically..(but that is the problem..)
Thnx in advance!
I'm not exactly sure what you want to achieve, but my guess is you have trouble with saving player points.
I've updated your plunkr. Basically instead of passing primitive values:
$scope.selectPlayer = function(name, points, asists, rebounds) { ... }
you should pass object reference:
$scope.selectPlayer = function(player) { ... }

Resources