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"}
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.
regex ('^h.') should work on this. To get row with name h.
Related
I am new to react and javascript. Here I am trying to use the lodsh function.
I have an array of object which looks like ,
const data = [{
"Id": "1",
"testone": 100,
"test": 40,
"Original": {
"Id": "11"
},
"__Parent__": {
"Id": "20",
"Status": "INP"
}
}, {
"Id": "2",
"testone": 120,
"test": 20,
"Original": {
"Id": "10"
},
"__Parent__": {
"Id": "21",
"Status": "Book"
}
},{
"Id": "3",
"testone": 110,
"test": 140,
"Original": {
"Id": "11"
},
"__Parent__": {
"Id": "20",
"Status": "INP"
}
}, {
"Id": "4",
"testone": 100,
"test": 40,
"Original": {
"Id": "11"
},
"__Parent__": {
"Id": "20",
"Status": "Val"
}
}]
Here, I have one function which has the product Id . which I am passing from another function =>
cont value = (PID, data) => {
}
So, this function ,
I need do sum , where first I need to take all the object which has the same Id as PID. The Id from object is to be Original.ID. If these matches then after that ,I need to check the status of that objects like , is status is either INP or BOOK then for summation need to take the
testone key value or else need to take the `test` key value.
So, In the given example it will be like ,
Id is 11 which is passed to a function and in the given object 3 objects where it matches.
Now,
while returning sum it will be like ,
100 + 100 + 40 which will be 240.
So, How do I do this . thanks .
I think it's best to do it with Array.reduce if you support IE9 and after.
const sum = data.reduce((total, item) => {
if (item.Original.Id !== PID) return total;
const { status, testone, test } = item;
let addition = 0;
if (status === "INP") addition = testone;
else if (status === "BOOK") addition = test;
return total + addition;
}, 0);
I am fairly new to Vue and JS but I am making API calls and getting a JSON response then sending the response to an empty array. How do I get the ID of each object in the array?
The array that the response is being pushed to is structured like this
groups: [
{
"id": "0",
"name": "a",
"price": 5
},
{
"id": "1",
"name": "b",
"price": 5
},
{
"id": "2",
"name": "c",
"price": 5
}
]
I'd like to pull the Id of each object and push the values to an empty array
for(var group in this.groups) {
if (this.groups.hasOwnProperty(0)) {
this.group = this.groups[0];
this.groupsId.push(this.innerObj);
}
}
The error I'm getting is saying Cannot read property '0' of undefined at eval
Ideally I'd like an array that has all the Ids of each object.
this.groups.hasOwnProperty(0) should be group.hasOwnProperty('id')
Use Array.prototype.map() to iterate over an array of objects and collect every ID into a new array:
const res = {
groups: [{
"id": "0",
"name": "a",
"price": 5
},
{
"id": "1",
"name": "b",
"price": 5
},
{
"id": "2",
"name": "c",
"price": 5
}
]
};
const ids = res.groups.map(obj => { // you use this.groups
if(obj.hasOwnProperty('id')) return obj.id;
});
console.log(ids)
There is the Array.map() method:
this.groupsId = this.groups.map(i => i.id);
If you already have elements in this.groupsId you can append the ids using Array.concat():
this.groupsId = this.groupsId.concat(this.groups.map(i => i.id));
You can use Array.prototype.reduce to loop and check if there's id.
const groups = [
{"name": "a","price": 5},
{"id": "1","name": "b","price": 5},
{ "id": "2","name": "c","price": 5}
];
const list = groups.reduce((groupIds, group) => group.id ? [...groupIds, group.id] : groupIds, []);
console.log(list);
This is my JSON response . I am able to splice out elements from controller side using something like this . Now comes a situation where my employees can have same employee id but different Type . So i would like to remove itesm from the response by comparing both Id & type. For example I need to remove the emplooyee with Id ABC and type D only . How can i splice them out how can i proceed
var searchresponse = [{
"items": [{
"employeeId": "ABC",
"type": "D",
"alive": "Yes"
}, {
"employeeId": "ABC",
"type": "P",
"alive": "Yes"
}, {
"employeeId": "NPK",
"type": "D",
"alive": "Yes"
}, {
"employeeId": "PKN",
"type": "A",
"alive": "Yes"
}],
"more": false
}];
var data1 = ["ABC"];
var data2 = ["D"] //- how to splice ABC also comparing the D
var items = searchresponse[0].items;
for (var i = items.length - 1; i >= 0; i--) {
if (data1.indexOf(items[i].employeeId) != -1) {
items.splice(i, 1);
}
}
If i understand u right.. will it be ok to just extend the if clause?
if (data1.indexOf(items[i].employeeId) != -1 && data2.indexOf(items[i].type) != -1)
Using array.prototype.filter method
var filterd =searchresponse[0].items.filter(function (item) {
return item.employeeId == "ABC"&& item.type== "D"
})
You may Also use underscore.js simple javascript library in your case
var filterd=_.where(searchresponse[0].items, {employeeId: "ABC", type: "D"});
will give you
[{
"employeeId": "ABC",
"type": "D",
"alive": "Yes"
}]
Check this working fiddle
Am having a json like below,
[
{
"id": "1",
"freq": "1",
"value": "Tiruchengode",
"label": "Tiruchengode"
},
{
"id": "2",
"freq": "1",
"value": "Coimbatore",
"label": "Coimbatore"
},
{
"id": "3",
"freq": "1",
"value": "Erode",
"label": "Erode"
},
{
"id": "4",
"freq": "1",
"value": "Madurai",
"label": "Madurai"
},
{
"id": "5",
"freq": "1",
"value": "Salem",
"label": "Salem"
},
{
"id": "6",
"freq": "1",
"value": "Tiruchirappalli",
"label": "Tiruchirappalli"
},
{
"id": "7",
"freq": "1",
"value": "Tirunelveli",
"label": "Tirunelveli"
}
]
I need to pattern match it with label item in this json (ie), If I type tiru, then it has to result label items having tiru substrings in it.If its a single item array I know how to pattern match and sort it. Here am completely unaware that, how to pattern match using label item in the array. Is it possible to?. I need to do with Pure javascript, any help guys?
You can use the functional array methods introduced in JavaScript 1.6, specifically filter:
var search = 'tiru';
var results = obj.filter(function(item) {
var a = item.label.toUpperCase();
var b = search.toUpperCase();
return a.indexOf(b) >= 0;
});
If you wanted labels only, you can then use map to return only that property alone:
var labels = obj.filter(function(item) {
var a = item.label.toUpperCase();
var b = search.toUpperCase();
return a.indexOf(b) >= 0;
}).map(function(item) {
return item.label;
});
Essentially, filter is a method available to any Array which returns a new Array containing only those members for which the supplied function return true.
JSON.parse() will help convert the jsonString to JsonObject then just iterate the object use indexOf for pattern matching.
var jsonString = '[{"id": "1","freq": "1","value": "Tiruchengode","label": "Tiruchengode"},{"id": "2","freq": "1","value": "Coimbatore","label": "Coimbatore"},{"id": "3","freq": "1","value": "Erode","label": "Erode"},{"id": "4","freq": "1","value": "Madurai","label": "Madurai"},{"id": "5","freq": "1","value": "Salem","label": "Salem"},{"id": "6","freq": "1","value": "Tiruchirappalli","label": "Tiruchirappalli"},{"id": "7","freq": "1","value": "Tirunelveli","label": "Tirunelveli"}]';
var jsonObjects = JSON.parse(jsonString);
var pattern = "tiru";
for(var key in jsonObjects){
var label = jsonObjects[key].label.toUpperCase();
if(label.indexOf(pattern.toUpperCase()) != -1){
document.write(label+"<br/>");
}
}
"category": [{
"id": 28,
"name": "Dogs"
},
{
"id": 14,
"name": "Cats"
},
{
"id": 878,
"name": "Sheep"
}],
I have the above JSON parsed (using .ajax and jsonp as callback) and I would like to join all the values of "name" into a string. i.e. "Dogs, Cats, Sheep". How can I do this? I have tried simple join on "category" and name, i.e.
var cats = categories.join(", ");
OR
var cats = categories.name.join(", ");
But since we are looking at it's members and their string values, it doesn't work.
This looks like a job for $.map!
var data = {
"category": [{
"id": 28,
"name": "Dogs"
},
{
"id": 14,
"name": "Cats"
},
{
"id": 878,
"name": "Sheep"
}]
}
var cats = $.map(data.category, function(v){
return v.name;
}).join(', ');
var text = "";
for(var i=0; category.length; i++)
{
text += category[i].name;
if(i!=category.length-1)
text += ", ";
}
Simpler, shorter version:
const category = [{
"id": 28,
"name": "Dogs"
},
{
"id": 14,
"name": "Cats"
},
{
"id": 878,
"name": "Sheep"
}]
let cats = category.map((item) => {
return item.name;
}).join(", ");
On the first part, the map function will return a string array with the contents item.name.
[ "Dogs", "Cats", "Sheep" ]
Since on arrays we have the ability to call join that will put all the items in array together but separated by whatever we pass to the join (in this case we have ", " it will separate by a comma and a space)
In the end we have:
Dogs, Cats, Sheep