I have a object like this
let obj = {'fruits_[apple,banana]':'This include Apple and Banana Both'}
But i only have apple as key to access
eg :: obj['fruits_\apple\]
---> this is not working
does anyone have idea how we can access key using regex??
CodePudding user response:
It depends how exact you want to be with your regex, but something like the below will work in the example given
const obj = {'fruits_[apple,banana]':'This include Apple and Banana Both'}
function findValue(obj, partialKey){
var item = Object.entries(obj).find( ([k]) => {
return k.match("fruits.*" partialKey ".*");
});
return item?.[1]
}
console.log(findValue(obj,"apple"));
console.log(findValue(obj,"banana"));
console.log(findValue(obj,"orange"));
Note that this will also work with partial key ban
which may or may not be what is required. You need a more exact regex to only support whiole words.
CodePudding user response:
If you are the one responsible for creating obj
, I suggest using 2 separate keys instead of one key that contains a list.
const obj = {
fruits_apple: "This include Apple and Banana Both",
fruits_banana: "This include Apple and Banana Both",
};
This makes accessing the value as easy as obj[`fruits_${fruit}`]
where fruit
is a variable containing either "apple"
or "banana"
.
This works best if you treat obj
as immutable, because updating obj.fruits_apple
will not automatically update obj.fruits_banana
. So you are responsible for keeping the values in sync.
This can be easily addressed by wrapping the values in an object that acts as a reference.
const value = { value: "This include Apple and Banana Both" };
const obj = { fruits_apple: value, fruits_banana: value };
The above allows you to update both fruit_apple
and fruits_banana
at the same time, even if you only have access to a single fruit.
obj.fruits_apple.value = "Some new value";
Will also update obj.fruits_banana
, since both refer to the same wrapper object.
const value = { value: "This include Apple and Banana Both" };
const obj = { fruits_apple: value, fruits_banana: value };
obj.fruits_apple.value = "Some new value";
console.log(obj.fruits_apple.value);
console.log(obj.fruits_banana.value);
This wrapper object is only needed if you plan to mutate the values though.