My json array:
[{"id":"7","name":"hello"},{"id":"7","name":"shan"},{"id":"7","name":"john"}
{"id":"7","name":"hello"}]
I want to get a new array that matches a regular expression on name
starting with a letter.
I am using regexp but i don't know how to implement it.
Here is my code:
var newitem=_.filter(result,item=>item.name='hello');
console.log(newitem);
But it returns with only strict match of name
.
Please help me to modify the above so that the result is a new array as described.
Expected output
when a usertype letter h
it shows only the row
{"id":"7","name":"hello"}
My json array:
[{"id":"7","name":"hello"},{"id":"7","name":"shan"},{"id":"7","name":"john"}
{"id":"7","name":"hello"}]
I want to get a new array that matches a regular expression on name
starting with a letter.
I am using regexp but i don't know how to implement it.
Here is my code:
var newitem=_.filter(result,item=>item.name='hello');
console.log(newitem);
But it returns with only strict match of name
.
Please help me to modify the above so that the result is a new array as described.
Expected output
when a usertype letter h
it shows only the row
{"id":"7","name":"hello"}
Share
Improve this question
edited May 31, 2016 at 18:02
Timo Tijhof
10.3k6 gold badges37 silver badges53 bronze badges
asked Feb 19, 2016 at 4:56
Blessan KurienBlessan Kurien
1,6659 gold badges33 silver badges64 bronze badges
3
|
2 Answers
Reset to default 14To check if the name
starts with a string, you can use RegExp#test
with regex.
var newItem = _.filter(result, obj => /^[a-zA-Z]/.test(obj.name));
The regex ^[a-zA-Z]
will check if the name starts with alphabet.
var arr = [{
"id": "7",
"name": "hello"
}, {
"id": "7",
"name": "shan"
}, {
"id": "7",
"name": "jhon"
}, {
"id": "7",
"name": "hello"
}, {
id: 10,
name: '$haun'
}];
var newItem = _.filter(arr, obj => /^[a-zA-Z]/.test(obj.name));
console.log(newItem);
<script src="https://cdnjs.com/libraries/lodash.js/"></script>
Same code can be written using Array#filter
.
arr.filter(obj => /^[a-zA-Z]/.test(obj.name));
var arr = [{
"id": "7",
"name": "hello"
}, {
"id": "7",
"name": "*shan"
}, {
"id": "7",
"name": "jhon"
}, {
"id": "7",
"name": "hello"
}, {
id: 10,
name: '$haun'
}];
var newItem = arr.filter(obj => /^[a-zA-Z]/.test(obj.name));
console.log(newItem);
document.body.innerHTML = '<pre>' + JSON.stringify(newItem, 0, 4) + '</pre>';
Update:
when a usertype letter h it shows only the row
You can use
_.filter(result, obj => /^h/.test(obj.name));
Use i
-case insensitive flag to match the alphabet irrespective of the case. That'll match both h
and H
.
regex ('^h.') should work on this. To get row with name h.
name
start with any letter? – Tushar Commented Feb 19, 2016 at 5:01item.name='hello'
will assign the string value. You need to use==
or===
. – Tushar Commented Feb 19, 2016 at 5:09name
starts withh
. – Tushar Commented Feb 19, 2016 at 5:32