Getting values ​​from an array that matches a regex using lodash

My json array is:

[{"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 the regular expression on name, starting with a letter.

I am using regexp , but I do not know how to implement it.

Here is my code:

var newitem=_.filter(result,item=>item.name='hello');
 console.log(newitem);

But he only comes back with a strict match name.

Please help me modify the above so that the result is a new array as described.

Expected Result

when a custom type letter honly shows a string

{"id":"7","name":"hello"}
+4
source share
2 answers

, name , RegExp#test .

var newItem = _.filter(result, obj => /^[a-zA-Z]/.test(obj.name));

^[a-zA-Z] , .

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>
Hide result

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>';
Hide result

Update:

h

_.filter(result, obj => /^h/.test(obj.name));

i , . h, h.

+9

regex ('^ h.') . h.

0

Source: https://habr.com/ru/post/1629498/


All Articles