Blessan Kurien Blessan Kurien - 6 months ago 476
JSON Question

Getting values from array that matches a regular expression using lodash

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"}

Answer

To 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.

Comments