Map the values in object with the given value in react - javascript

I am new to the react, Here I have one array of object which is like
const bgStatus =
[{
Id: "809"
Name: "PRE"
Description: "PRE"
Value: "VP:PRE"
},
{
Id: "809"
Name: "CLO"
Description: "CLO"
Value: "VP:CLO"
},
{
Id: "809"
Name: "BU"
Description: "BU"
Value: "VP:BU"
}
]
Now , In this I have one method through which I get the value which is VP:PRE or VP:BU or VP:CLO
Now, I have the following function
getmsg = (bgSt, tobeChange, current) => {
return `Are you sure you want to change to ${tobeChange}? not possible to go ${current} `
}
Now, In this both the status tobeChange and current comes in a VP:PRE in this format. Now, I want to use the Description from that array for that value like for VP:PRE , it should be 'PRE' in the return value. Now ,
I have one solution which is like creating a key value map and then map it. But, I can not hard code that values over here.
So, and also don't want to use the includes or contains things.
Result which I want - When I am calling the function
getmsg this time in params I am passing , tobeChange is `"VP:PRE"`, current is "VP_BU" and bgStatus is the array of object.
Now in return I should get this message ,
`Are you sure you want to change to PRE not possible to go BU `
The values VP_PRE should get replaced with the description PRE

Well if you are always getting the two variables :
tobeChange=VP:something_to_change
current=VP:something
It has nothing to do with react it is javascript traitement
I suggest you use the function split here is an example :
getmsg = (tobeChange, current) => {
toChange=tobeChange.split(":")
tobeChange=toChange[1]
curr=current.split(":")
current=curr[1]
return `Are you sure you want to change to ${tobeChange}? not possible to go ${current} `
}
tobeChange="VP:something_to_change"
current="VP:something_current"
console.log(getmsg(tobeChange, current))

Related

update data with useState in React js

I am new to react. I have faced one issue and not able to solve it. I am looking for your help.
I have an array which I have listed below. All data are looped and displayed in the view. From my current array, I want to update the count of dietry array[] which is inside the fruits array.
This is my useState
const [foods, setFood] = useState(fruits)
if I console.log(foods) it gives data as below.
fruits: [
{
id: 1,
name: 'Banana',
family: 'abc',
price: 2.99,
isEnabled: true,
dietary: [
{
id:1,
disabled: false,
group: null,
selected: false,
text: 'N/A',
value: '858090000',
count:0
},
{
id:2,
disabled: true,
group: null,
selected: true,
text: 'N/A',
value: '80000',
count:0
},
}
This data are looped in a view page and there is onClick handleIncrement method which should increment the count of dietary array of index 0 or index1 etc whichever index sent from handleIncremnt() method.
This is my method
const handleIncrementCount = (dietary_index) => {
setFood(foods =>
foods.map((food,index) =>
dietary_index === food[index] ? {...food, qty:food.count+1}:food
)
);
}
I am not able to increase the count, in my view page counts are 0 even if i click the increment button.It shows some error within map
Any help is highly appreciated
I ma looking for a solutions
There are a few issues with your handleIncrementCount function. Firstly, you are trying to use the dietary_id parameter to find the correct food object to update, but you are using it to access the index property of the food object instead. This will always return undefined, and so the function will not be able to find the correct object to update.
Secondly, you are trying to update the qty property of the food object, but this property does not exist in the food object. Instead, you need to update the count property of the correct dietary object inside the food object.
Here is how you can fix these issues:
const handleIncrementCount = (dietary_id) => {
setFood(foods =>
foods.map(food => {
// Find the dietary object with the correct id
const dietary = food.dietary.find(d => d.id === dietary_id);
// If the dietary object was found, increment its count
if (dietary) {
dietary.count += 1;
}
// Return the updated food object
return food;
})
);
};
With this change, the handleIncrementCount function should be able to find the correct food object and update the count property of the correct dietary object.
Note that this function is using the Array.prototype.map() and Array.prototype.find() methods to transform the foods array and find the correct dietary object to update. These methods are commonly used in JavaScript to transform and find elements in arrays. It is worth reading up on these methods and understanding how they work in order to better understand this code.

Is there a quicker way to copy a value in a key of data object to a new key in the same data object in javascript?

I'm experimenting with how I can make my code more concise when I have a piece of an array of objects received from an API endpoint. This is the initial variabel:
let stringOptionsOutlet = [];
Then I want to make a new key called "value". This is how I normally do (which I think is okey but I believe there must be some disadvantages in comparison with other techniques you might come up with):
stringOptionsOutlet = [...response.data.outlet]; // 1. this is the data I get from an API endpoint, I copy it with the spread operator
stringOptionsOutlet.map((v) => return { ...v, value: "" }; ); // 2. then I make the same new value in every single data object inside the array stringOptionsOutlet
Object.entries(stringOptionsOutlet).forEach((e) => {
e[1].value = e[1].id; // 3. copy the value of id to the new key
});
The data before I map the data:
[
{
label: "A1-1",
id: "1",
},
{
label: "B2-1",
id: "4",
},
]
After the mapping (step number 2 and number 3):
[
{
label: "A1-1",
id: "1",
value: "1",
},
{
label: "B2-1",
id: "4",
value: "1"
},
]
Could you also please explain the benefits and shortcomings of the techniques? Thank you.
What you're doing will work but there are certainly some unnecessary steps as written. There's no need to copy the API response data into an array and then change the array contents when you can map the API response itself.
// You can do steps 1 2 and 3 all in 1 .map()
const stringOptionsOutlet = response.data.outlet.map(v => {
return {
...v,
value: v.id
}
})
The downside of doing it all in 1 way is that if you want to do some more complex logic that single .map call could get very cluttered and maybe it'd be simpler to introduce a separate step, with the caveat that you'd then process the data a second time.
Try this:
stringOptionsOutlet.map((v) => ({ ...v, value: v.id }));

make the query dynamically to change using sanity.io groq

Hi there I'm trying to make a post request where I want to update one field on sanity.io
this is my query
patch: {
id: "f6c46b53-9313-4354-a4d6-7a40b06ee4c0",
set: {
`rewardItem[_key == \"${key}\"].lastTimeReward`: "TEst",
},
}
but this won't let me even run my project,
its giving me this error on console.log: Unexpected token;
When I do my query like this, it works
patch: {
id: "f6c46b53-9313-4354-a4d6-7a40b06ee4c0",
set: {
"rewardItem[_key == \"e88959e43ce7\"].lastTimeReward": "Test",
},
}
}]
Thanks a lot.
Your set-property is an object, and you can't enter a dynamic key directly into the object. To do what you are trying to do here, you can wrap the dynamic key in square brackets like this. That should give you the output you desire
const variable = "example"
const a = { [`template ${variable}`]: "value" }
console.log(a)

Using multiple filters on a dynamically generated table with pure JavaScript

I have a table that is dynamically generated using PHP and a MySQL table/database... I also have figured out how to use filters. The problem is that it only lets you use one filter at a time... Here is a screenshot of what I mean: screenshot
You can only filter by description or by date... not both.
Is there some way to do this? I can't really provide you any HTML/JavaScript code as you won't see anything because the table data comes from a database but let me know if you need any more detail...
Thanks!
If I understood your question properly, you can do something like this:
Let's assume we have an array of objects
const data = [
{
id: 0,
date: '1609084588132',
description: 'something'
},
{
id: 1,
date: '1609087588132',
description: 'anything'
},
{
id: 2,
date: '1609087588132',
description: 'anything'
}
]
And to filter this array by two properties, you can do something like:
const filteredData = data.filter((item) => {
if (item.date > 'some date' && item.description.includes('anyth')) {
return true;
}
return false;
});
console.log(filteredData)
I think you got an idea, we filtered the array above with two conditions: id must be bigger than 0 and description string must contain 'anyth'.

How to update the value of a single property within a state object in React.js?

So I have the following object structure:
const SamplePalette = {
id: 1,
name: "Sample Palette",
description: "this is a short description",
swatches: [
{
val: "#FF6245",
tints: ["#FFE0DB", "#FFA797"],
shades: ["#751408", "#C33F27"]
},
{
val: "#FFFDA4",
tints: ["#FFFFE1"],
shades: ["#CCCB83"]
},
{
val: "#BFE8A3",
tints: ["#E7FFD7"],
shades: ["#95B77E"]
}
]
}
Let's imagine that this object is managed by the state of my app like this:
this.state = {
currentPalette: SamplePalette,
}
My question is how would I go about updating the val property of a given swatch object in the swatches array? Or more generally - how do I only update pieces of this object?
I tried using the update helper as well as to figure out how Object.assign() works, however I've been unsuccessful and frankly can't really grasp the syntax by just looking at examples.
Also, since I'm going to be modifying this object quite a lot, should I look into maybe using Redux?
[EDIT]
I tried #maxim.sh suggestion but with no success:
this.setState(
{ currentPalette: {...this.state.currentPalette,
swatches[0].val: newValue}
})
Consider you have new new_swatches
I think the clearer way is to get array, update it and put back as:
let new_swatches = this.state.currentPalette.swatches;
new_swatches[0].val = newValue;
this.setState(
{ currentPalette:
{ ...this.state.currentPalette, swatches: new_swatches }
});
Also you have : Immutability Helpers or https://github.com/kolodny/immutability-helper
Available Commands
{$push: array} push() all the items in array on the target.
{$unshift: array} unshift() all the items in array on the target.
{$splice: array of arrays} for each item in arrays call splice() on the target with the parameters provided by the item.
{$set: any} replace the target entirely.
{$merge: object} merge the keys of object with the target.
{$apply: function} passes in the current value to the function and updates it with the new returned value.

Categories

Resources