I'm working with an object containing multiple network interfaces with the interfaces' names as keys and then interfaces' informations as values :
What I would like to do is a Vue.js computed property to filter this object by Keys and create arrays that contain all GigabitEthernet separately for example so I can iterate over it in my template.
I thinked about using Regex, here is the one that I use and match the interfaces I want to put in a separate array :
const regex = /^(Te|GigabitEthernet|FastEthernet)+\s?([0-9]+\/){0,}[0-9]+$/g;
The problem is that the main object received from API isn't an array so I can't use find() or filter() functions over it...
If anyone as any idea it would be nice, thanks !
EDIT :
After trying Jaromanda's solution :
It returns only 1 line out of 2...
Here is the code :
const regex = /^(Ten|GigabitEthernet|FastEthernet)\d+[/]?[\d+]?[/]?[\d+]?[.]?[\d+]?[/]?[\d+]?[/]?[\d+]?[:]?[\d+]?$/g;
var rslt = {};
Object.fromEntries(
Object.entries(this.cmdResult).filter(([key, value]) => {
if (regex.test(key)) {
rslt[key] = value;
}
})
);
return rslt;
Here is a screenshot of current output at the left and expected output at the right :
EDIT 2 :
Here is what happens when I console log the regex results with the associated key :
As you can see only 1 out of 2 is true...
1 Answer 1
This is other solution, using map.
const cmdResult = {
"GigabitEthernet1/0/2": {name: ""},
"GigabitEthernet1/0/3": {name: ""},
"GigabitEthernet1/0/4": {name: ""}
}
const regex = /(GigabitEthernet||FastEthernet\d+(\.\d)*)/i;
const rslt = {};
Object.keys(cmdResult)
.filter((key) => regex.test(key))
.map(prop => rslt[prop] = cmdResult[prop])
console.log(rslt);
Object.fromEntries(Object.entries(object).filter(([key, value]) => your code to filter))
test
will advance thelastIndex
property of the regex when used with the global flag (g
). For this reason the next match fails, because it starts of too far into the string to find a match. Either remove theg
flag from the regex, create a new regex for each test or reset thelastIndex
property to0
before eachtest
.