Has anyone tried getting a particular value inside a prop using a variable?
Normally, getting a particular data in props goes like
const dataValue = props.table.data.rowData.account_number
However in this instance I need the last part of the props to be a variable, because
the account_number value is not fixed and the name varies.
So is there a way that I use a variable instead of adding a fixed name on the past part of the prop call?
Like so:
let theVariable = *somethingNew*;
const dataValue = props.table.data.rowData.theVariable
You can do this through property bracket access:
let theVariable = somethingNew;
const dataValue = props.table.data.rowData[theVariable]
This can also be used during object creation:
const dataValue = {
[theVariable]: {}
}
Yes. You can do like this:
let theVariable = *somethingNew*;
const dataValue = props.table.data.rowData[theVariable];
Related
I have a series of commonly named properties, and I'd like to have the un-common part of the name used in other places. I know that wording is a little convoluted, but perhaps an example will help. What I want is something like:
const MyComponent = ({lgProp, xlProp, mdProp, smProp, defaultProp}) => {
let current = defaultProp;
let myString = 'foo';
['sm', 'md', 'lg', 'xl'].forEach(size => {
const newValue = // somehow get the value of the property ${size}Prop
if (current !== newValue) {
myString += ` ${size}: ${newValue}`;
current = newValue;
}
});
}
The canonical answer to this type of question seems to be here, but all of the answers there either refer to dynamically referencing keys in objects, or dynamically referencing variables in pure JS in the Window or this scope. I can't seem to make any of them work for referencing property names.
There are also several sections on dynamically creating property names for components, but that's the wrong direction for me.
Things I've tried:
newValue = `${size}Prop`; // string
newValue = [`${size}Prop`]; // string
newValue = [${size} + 'Prop']; // string
newValue = this[${size} + 'Prop'] // TypeError
I mean, there are only so many props, so I could just write a bunch of if statements, but that seems so inelegant. Is there an attractive/elegant way to variably reference the prop names?
This is mutating my redux state somehow. I don't know why:
allProducts is a state in my store with initial_state of [] and gets values from api call.
const [products, setProducts] = useState([])
const prevProducts = [...allProducts];
setProducts(prevProducts);
const updateProductPrice = (newPrice, index) => {
const newProducts = [...products];
newProducts[index].price = newPrice;
setProducts(newProducts);
console.log(allProducts);
}
When I console.log(allProducts), it's showing me an updated array that has the values of newProducts
I think what you are seeing has to do specifically with how JavaScript is storing object references inside your arrays. When you copy an array, you do not do a full re-creation of all the objects in it, even when using the spread operator, you are only copying the references to the objects at each index.
In other words, assuming they share matching indexes, each item at newProducts[i] === allProducts[i] - i.e. is the exact same object instance.
See, for example, https://javascript.info/object-copy and as well there are many references for "shallow" and "deep" copying for objects.
The objects are the same in memory even though I changed the reference.
"A variable assigned to an object stores not the object itself, but its “address in memory” – in other words “a reference” to it."
I used _.cloneDeep from https://lodash.com/docs/4.17.15#cloneDeep
So I changed my code to:
const prevProducts = _.cloneDeep(allProducts);
setProducts(prevProducts);
Another solution: In case you do not want to use lodash.clonedeep package, you can do the same using below:
const array = [{a: 1}]//initial array
const copy = array.map(item => ({...item}))
I have this problem which may sounds stupid but I don't really understand the whys.
I declare it as a variable: let [ randomQuoterState, setrandomQuoterState ] = useState([]); Then pass it into a component inside the return: <UserOutput set={setrandomQuoterState} current={randomQuoterState} number={1}/>
The following code is inside the component:
let toSet = [];
toSet[props.number] = quoteArray[Math.floor(Math.random() * quoteArray.length)];
let quote = props.current;
if (quote[props.number]){
delete quote[props.number];
console.log("deleted")
}else {
console.log("this does not exist");
}
console.log(typeof(toSet[props.number]));
console.log(toSet[props.number].lenght)
console.log(toSet[props.number]);
quote[props.number] = toSet[props.number][Math.floor(Math.random() * toSet[props.number].lenght)];
props.set(quote);
The Consol displays it as an array, but the typeof function says its an object, and it doesn't have a length property.
I would appreciate any help or explanation, I thought about it a lot, but I couldn't come up with anything.
Arrays are objects in Javascript. In fact, there is no array type.
To see if it is an array, you should try console.log((toSet[props.number]).constructor.name) and do your checks against toSet[props.number] instanceof Array.
Do not use (toSet[props.number]).constructor.name == 'Array' in your comparisons, because you could have something that has inherited from Array but whose constructor name is different.
In JavaScript both object and array are of type Object.
In case you want to determine exact type, you can use constructor property.
const data = {};
data.contructor.name === 'Object'; // Returns True
const data = [];
data.contructor.name === 'Object'; // Returns True
data.contructor.name === 'Object'; // Returns False
Above can used to determine String, Date etc as well.
Alternatively you can use libraries like lodash which has function for these things.
However that is overkill I guess.
Hope it helps.
So I'm pulling some data from my DB and it comes out in the form of an object. I'd like to take this object and turn it into separate constants. This is the object
(sorry for link, I dont have enough rep to post images)
https://i.imgur.com/ay7cI29.png
How can I take values out from the object and assign them to constants. I want to get the value of the field 'address' which is the apartment's address and assign it to a const called rent.
You can use destructuring for this very easily:
const { rent: address, ownerEmail, otherProperty1, otherProperty2 } = yourObject;
console.log(rent); //The address
You can use destructuring. So, let's say you only want the id from the object. You could do something like the following:
const { id } = await fetchMyData();
you can access the object properties like,
1.
const {ac, address} = yourObject;
2.
const ac = yourObject.ac;
const address = yourObject.address;
Hope this can help!
Here's a problem that is bothering me for a while.
I have a service provider to pass data to all views, everytime the sidebar is rendered. like this:
`
public function boot()
{
$userrole = array (DB::table('users')->where('id','=', Auth::id())->value('role'));
$menucase1 = [3,4,9,10];
$menucase2 = [1,2,3,10];
$menucase3 = [1,3,4,9,10];
$menucase4 = [4,9];
$commondata = compact('userrole','menucase1','menucase2','menucase3','menucase4');
view()->share('commondata', $commondata);
View::composer('sidebar', function ($view) {
$userrole = array (DB::table('users')->where('id','=', Auth::id())->value('role'));
$menucase1 = [3,4,9,10];
$menucase2 = [1,2,3,10];
$menucase3 = [1,3,4,9,10];
$menucase4 = [4,9];
$commondata = compact('userrole','menucase1','menucase2','menucase3','menucase4');
$view->with('commondata', $commondata);
});
}`
Doing a {{ dd($commondata) }} returns the correct values for the menucase arrays, but NULL for the $userrole
If i declare the same $userrole variable in a controller and call the variable in the view, the received data is correct.
Why is this happening?
Thanks in advance
Can't understand what are you actually trying to do.
If you want get user role as array, you can using pluck method:
$userRole = User::where('id', Auth::id())->pluck('role')->toArray();
But for current user you can just get the role
$userRole = [Auth::user()->role];
UPD: you also can do it in view without any sharing
{{ Auth::user()->role }}
If your user has many roles from a different table, and you have the relationship defined, you could do
$userrole = Auth::user()->roles->pluck('name');
//will return all the roles names in an array
//Replace name by the actual column you want from 'roles' table.