Reputation: 43
How to get specific value from array? i.e.
"Names": [
"Name[name]",
"Result[Type]",
"Validation[Option]",
"Status[Pointer]"
]
Output must be:
"Names": [
"name",
"Type",
"Option",
"Pointer"
]
Upvotes: 0
Views: 60
Reputation: 1539
substring and indexOf in action:
let newArray = [];
for(var i=0; i<array.length; i++){
var s = array[i];
var n = s.indexOf('[');
s = s.substring(n+1, s.length-1);
newArray.push(s);
}
OR
let newArray = [];
for(var i=0; i<array.length; i++){
newArray.push(array[i].substring(array[i].indexOf('[')+1, array[i].length-1));
}
Upvotes: 0
Reputation: 1061
You can loop through array and using following regex to get the desired output.
const array = [
"Name[name]",
"Result[Type]",
"Validation[Option]",
"Status[Pointer]"
];
var regexTest = new RegExp(/\[([^\]]+)\]/);
var newArray = array.map(e => regexTest.exec(e)[1]);
fiddle link
Upvotes: 0
Reputation: 3386
You can use substring method and based on the start and end bracket grab the subtring. To iterate on every element of array use map function, it creates a new array with the results of calling a provided function on every element in the calling array.
const arr = [
"Name[name]",
"Result[Type]",
"Validation[Option]",
"Status[Pointer]"
]
let result = arr.map((a)=>{ return a.substring(a.indexOf("[") + 1 , a.indexOf("]")) });
console.log(result);
Upvotes: 0
Reputation: 22203
Try like this:
export class AppComponent {
Names = [
"Name[name]",
"Result[Type]",
"Validation[Option]",
"Status[Pointer]"
]
constructor() {
var modifiedNames = this.Names.map(x => x.split('[').pop().split(']')[0])
console.log(modifiedNames)
}
}
See Stackbiltz Demo
Upvotes: 1
Reputation: 2330
const array = [
"Name[name]",
"Result[Type]",
"Validation[Option]",
"Status[Pointer]"
];
const newArray = array.map(e => /^\w+\[(\w+)\]$/.exec(e)[1]);
// ["name", "Type", "Option", "Pointer"]
Upvotes: 0