fetch the array having specific value - javascript

I have the json array value which have age and number.I want to create a new set of array which has {"num":2} in it (ie)need to return [{"age":2,"num":2},{"age":3,"num":2}]
var array_val='[{"age":1,"num":1},{"age":2,"num":2},{"age":3,"num":2}]';
console.log(array_val);
function fetchList(array_val) {
return array_val = {"num":1};
}
array_val.filter(fetchList)
console.log(array_val);

I see 2 issues in your code:
You don't parse your string to JSON
You have a wrong filter
function
var array_val='[{"age":1,"num":1},{"age":2,"num":2},{"age":3,"num":2}]';
console.log(array_val);
function fetchList(array_val) {
return array_val.num === 2; // return only records whose num is 2
}
// here you parse string into JSON and apply the filter
var data = JSON.parse(array_val).filter(fetchList);
console.log(data);

You need to use filter()
var fetched_object = array_val.filter(function(obj) {
return obj.num == 1;
});
Note: Like #NinaScholz said you need to JSON.parse the string so it is an array.

You need parse the JSON string JSON.parse() .And matching condition was wrong .num is the inner propery of the object .so you need to match a.num == 2 .Don't forget to add ==
var array_val='[{"age":1,"num":1},{"age":2,"num":2},{"age":3,"num":2}]';
console.log(array_val);
function fetchList(a) {
return a.num == 2;
}
var res = JSON.parse(array_val).filter(fetchList)
console.log(res);

This should do it
var array_val=JSON.parse('[{"age":1,"num":1},{"age":2,"num":2},{"age":3,"num":2}]');
console.log(array_val);
function fetchList(array_val) {
return array_val.num == 2;
}
array_val = array_val.filter(fetchList)
console.log(array_val);

This would work instead:
var requiredValue = array_val.filter(function(item) { return item.num === 2;
});

try this
var array_val=JSON.parse('[{"age":1,"num":1},{"age":2,"num":2},{"age":3,"num":2}]');
var newarr =[]
for(let i of array_val){
if(i.num == 2){
newarr.push(i);
}
}
console.log(newarr);

Related

split last two words and filter in javascript

I would like to know how to filter array of values using javascript
How to seperate the arrays with 'provider-send' and 'provider-receive'
var filterradio = id.filter(function(e){
return e.id.split("-")[0] == "provider-send"
})
var id=["provider-send-credit-transfer", "provider-send-debit-fund","provider-receive-credit-transfer","provider-receive-debit-fund"]
Expected Output:
result_sn: ["provider-send-credit-transfer", "provider-send-debit-fund"]
result_rcn:["provider-receive-credit-transfer","provider-receive-debit-fund"]
If it's always going to be "provider-receive-..." and "provider-send..." then you can do the following to separate them
for (i = 0; i < id.length; i++) {
if (id[i].split("provider-send-").length > 1) {
result_sn.push(id[i]);
} else if (id[i].split("provider-receive-").length > 1) {
result_rcn.push(id[i])
}
}
Try This :
var id = [ "provider-send-credit-transfer", "provider-send-debit-fund","provider-receive-credit-transfer","provider-receive-debit-fund" ] ;
var result_sn = [] , result_rcn = [] ;
for( value of id ) {
var twoWords = value.split('-',2).join('-') ;
if ( twoWords === "provider-send" )
result_sn.push( value ) ;
else if ( twoWords === "provider-receive" )
result_rcn.push( value ) ;
}
console.log( result_sn ) ;
console.log( result_rcn ) ;
Pass 2 as second parameter to split() and then again join() by -. The second parameter to split() specifies the max number of elements in the result array.
var id=["provider-send-credit-transfer", "provider-send-debit-fund","provider-receive-credit-transfer","provider-receive-debit-fund"]
var filterradio = id.filter(function(id){
return id.split("-",2).join('-') === "provider-send"
})
console.log(filterradio)
Using .filter() will require you to write 1 filter for every pattern you want to match have assigned to a variable.
Using .reduce() is recommended and is more easily expandable to support more patterns.
It may look intimidating at first but you're essentially using accumulator as the temporary variable that gets stored and brought forward to each iteration. And each iteration of the array will give you the current iterated value with currentValue.
I've added something-else as an example of adding new pattern.
var id = [
"provider-send-credit-transfer",
"provider-send-debit-fund",
"provider-receive-credit-transfer",
"provider-receive-debit-fund",
"something-else-credit-transfer",
"something-else-debit-fund"
];
const {
'provider-send': result_sn,
'provider-receive': result_rcn,
'something-else': result_ste
} = id.reduce(function(accumulator, currentValue) {
let prefix = currentValue.match(/^\w+-\w+/)[0];
return {...accumulator, [prefix]: (accumulator[prefix] || []).concat(currentValue)}
}, {});
console.log(result_sn);
console.log(result_rcn);
console.log(result_ste);
I suggest using reduce instead of the filter as reduce is used to reduce the array size into a single returned element.
Here I am reducing the array into an object which has two keys result_sn and result_rcn.
var id = ["provider-send-credit-transfer", "provider-send-debit-fund", "provider-receive-credit-transfer", "provider-receive-debit-fund"]
const result = id.reduce((obj, str) => {
if (str.match(/^provider-send/g))
obj['result_sn'].push(str);
else
obj['result_rcn'].push(str);
return obj;
}, {
'result_sn': [],
'result_rcn': []
});
console.log(result)

Converting a badly stringfied json to a json object

I have some data i am pulling from a web service. This is the string
(Body:'3886' MessageProperties [headers={}, timestamp=null,
messageId=null, userId=null, receivedUserId=null, appId=null,
clusterId=null, type=null, correlationId=null,
correlationIdString=null, replyTo=null,
contentType=application/x-java-serialized-object,
contentEncoding=null, contentLength=0, deliveryMode=null,
receivedDeliveryMode=PERSISTENT, expiration=null, priority=0,
redelivered=false, receivedExchange=,
receivedRoutingKey=bottomlesspit, receivedDelay=null, deliveryTag=62,
messageCount=0, consumerTag=amq.ctag-sCwfLaMEqWp2GkFwFrY1yg,
consumerQueue=bottomlesspit])
It looks like json but the key value pairs are almost fine but the most important key which is Body isn't like other keys as the string would tell.
I need to read the value of Body and be able to get the value like this
console.log(d.body);
//This above outputs the string as shown
obj = eval('{' + d.body + '}');
console.log(obj);
var match = "Body";
var val = obj.find( function(item) { return item.key == match } );
console.log(val);
How can i read the value of the key Body?.
Use this regular expression instead of a match Body:
\bBody:'(\d*)'
This will catch the Body number in group 1.
You can write a parser function get string and extract values. A very simple function is here. You can modify it also for all exceptions exist.
var str = `(Body:'3886' MessageProperties [headers={}, timestamp=null, messageId=null, userId=null, receivedUserId=null, appId=null, clusterId=null, type=null, correlationId=null, correlationIdString=null, replyTo=null, contentType=application/x-java-serialized-object, contentEncoding=null, contentLength=0, deliveryMode=null, receivedDeliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=, receivedRoutingKey=bottomlesspit, receivedDelay=null, deliveryTag=62, messageCount=0, consumerTag=amq.ctag-sCwfLaMEqWp2GkFwFrY1yg, consumerQueue=bottomlesspit])`;
function f(inp) {
var index = str.indexOf(inp),
endIndex;
for(var i = index; i < str.length; i ++) {
if(str[i] == ',') {
endIndex = i;
break;
}
}
var output = str.substr(index, endIndex).split('=');
return output;
}
console.log(f('consumerQueue'));
Why not use a regex to match and extract the Body.
Example:
const match = d.body.match(/Body:\'(.+)\'/)
if (match) {
const body = match[1] // This is the value of Body
} else {
// Unable to find Body, handle it here
}

How to remove function name from Javascript object

I have a Leaflet map and I want to edit a polygon. I successfully do this, but when I finish the editing, the coordinates are saved like:
,,LatLng(44.94633, 26.00773),LatLng(44.93588, 25.94318),LatLng(44.94245, 25.90645),LatLng(44.91814, 25.87074),LatLng(44.91328, 25.9346),LatLng(44.90015, 25.97031),LatLng(44.90112, 26.11519)"
I only want to have the coordinates without function name. How can I do this? Thanks!
map.on("dragend", function(e){
poligon = polygon.getLatLngs();
poligon1 = poligon.toString();
$('#geo').val(poligon1);
console.log(poligon1);
});
Dont use toString() u will get an array of objects
var arr=[];
console.log(polygon.getLatLngs());
for(var i=0;i<arr.length;i++){
arr=polygon.getLatLngs();
console.log(arr[i].lat);
console.log(arr[i].lng);
console.log("("+arr[i].lat +","+arr[i].lng+")");
}
Resolved it by writing one line:
poligon = polygon.getLatLngs();
//this is what I added
poligon2=poligon.join(',').match(/([\d\.]+)/g).join(',')
You can override toString method of LatLng prototype at your project init
L.LatLng.prototype.toString = function() {
return '(' + this.lat + ',' + this.lng + ')';
}
Then you'll see output like this cause Array.toString() recursively call toString() on every element in collection.
(44.94633, 26.00773),(44.94633, 26.00773)
I'll just add an answer.
This should work in general: give it a string, it will try to find all numbers, and return them in an array.
<script>
var mystring = "LatLng(44.94633, 26.00773),LatLng(44.93588, 25.94318),LatLng(44.94245, 25.90645),LatLng(44.91814, 25.87074),LatLng(44.91328, 25.9346),LatLng(44.90015, 25.97031),LatLng(44.90112, 26.11519)";
function isNumeric(input) {
return (input - 0) == input && input.length > 0;
}
// reads a string, finds numbers (float), returns the numbers in an array
function numbersInString(string) {
var s = 0, temp=0, result = [];
for(var i=0; i<string.length; i++) {
s = string.substr(i,1); // search 1 character, see if it's a number (digit)
if(isNumeric(s)) {
// parseFloat wil read as many characters as it can, and drop the rest
temp = parseFloat(string.substr(i));
// okay, now skip the length of the float
i = i + temp.toString().length ;
result.push(temp);
}
}
return result;
}
window.onload = function() {
var numbers = numbersInString(mystring);
document.getElementById('log').innerHTML += numbers.join(',');
}
</script>
<div id="log"></div>

Implementing wildcard at end of a string

I looked through a number of posts (and other websites) and I seem to have a hit a roadblock. I have the following array:
var data_dictionary = ["youtube.com", "facebook.com", "youtube.com/feed/subscriptions", "twitter.com"]
I'm trying to return data for everything that has youtube.com*. Below is the relevant snippet of my function:
var result = []
for (var i=0; i<data_dictionary.length; i++) {
if (data_dictionary[i].page == /^youtube.com/) {
result.push (data_dictionary[i].page,data_dictionary[i].share)
}
}
break;
}
return result
The problematic area is in the if clause (/^youtube.com/). How can I receive the following return:
["youtube.com" , "youtube.com/feed/subscriptions"]
You can use Array.prototype.filter() method to filter array and RegExp.prototype.test() to check for match.
var data_dictionary = ["youtube.com", "facebook.com", "youtube.com/feed/subscriptions", "twitter.com"];
function check(data_dictionary) {
return data_dictionary.filter(function(v) {
return /^youtube\.com/.test(v);
// using indexOf
// v.indexOf('youtube.com') == 0;
});
}
console.log(check(data_dictionary));
FYI: Your if condition will be only true if the string is '/^youtube.com/'. ie, ('/^youtube.com/' == /^youtube.com/) === true. Your code will work if you changed the if condition to /^youtube.com/.test(data_dictionary[i]). Also in the provided data page and share properties are undefined only plain strings are the element.
Using the same approach that you had before. However using ".filter" won't be a bad idea, but I will suggest you compare their benchmark
var data_dictionary = ["youtube.com", "facebook.com", "youtube.com/feed/subscriptions", "twitter.com"];
var pattern = /^youtube.com/;
var result = [];
var i = 0;
function loop (args) {
for (i; i < args.length; i++) {
if (pattern.test(args[i])) {
result.push(args[i]);
}
}
return result;
}
console.log(loop(data_dictionary)) // ["youtube.com" , "youtube.com/feed/subscriptions"]
Comparing the speed below I would suggest you use the approach above
No need for regex here you can do like this;
var data_dictionary = ["youtube.com", "facebook.com", "youtube.com/feed/subscriptions", "twitter.com"],
filtered = data_dictionary.filter(e => !!~e.indexOf("youtube.com") && e);
document.write("<pre>" + JSON.stringify(filtered) + "</pre>");
Or if you want a faster solution still with Array methods then
var data_dictionary = ["youtube.com", "facebook.com", "youtube.com/feed/subscriptions", "twitter.com"],
filtered = data_dictionary.reduce((p,c) => !!~c.indexOf("youtube.com") ? p.concat(c):p,[]);
document.write("<pre>" + JSON.stringify(filtered) + "</pre>");

how to get length of json encoded array in javascript?

I have a json encoded array like this:
{
"ar0":"{\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}",
"ar1":"{\"start\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"end\":{\"lat\":23.0420584,\"lng\":72.67145549999998},\"waypoints\":[[23.02237,72.6500747]]}",
"ar2":"{\"start\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"end\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"waypoints\":[[23.0016629,72.58898380000005]]}"
}
my quetion is :
(1) How to find length of this array? //here it is 3
(2) How to use it's value?
//for example:for as0 the value is {\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}
javascript code where i use upper things :
function setroute(os)
{
var wp = [];
for(var i=0;i<os.waypoints.length;i++)
wp[i] = {'location': new google.maps.LatLng(os.waypoints[i][0], os.waypoints[i][1]),'stopover':false }
ser.route({'origin':new google.maps.LatLng(os.start.lat,os.start.lng),
'destination':new google.maps.LatLng(os.end.lat,os.end.lng),
'waypoints': wp,
'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK')ren.setDirections(res);
})
}
function fetchdata()
{
var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
jax.open('POST','process.php');
jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
jax.send('command=fetch')
jax.onreadystatechange = function(){ if(jax.readyState==4) {
alert(JSON.parse(jax.responseText).ar0);
try {
console.log(jax.responseText);
//it is not work
for(var i=0;i<JSON.parse(jax.responseText).length;i++)
{
setroute( eval('(' + jax.responseText + ')') );
}
}
catch(e){ alert(e); }
}}
}
Your JSON is not an array, but an object. If you want it to be an array, it should be something like this:
[
"{\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}",
"{\"start\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"end\":{\"lat\":23.0420584,\"lng\":72.67145549999998},\"waypoints\":[[23.02237,72.6500747]]}",
"{\"start\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"end\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"waypoints\":[[23.0016629,72.58898380000005]]}"
]
Then, you can get a javascript array as follows:
var array = JSON.parse(jax.responseText);
And access values as follows:
array[0]
array.length
EDIT: In order to have a real JSON array with the PHP json_encode method, see this related question.
With this modification you will be able to use all the possibilities of JS array without workaround.
Objects in JavaScript don't have a .length property like Arrays do.
In ES5 you can do: Object.keys({}).length; // 0
The other solution would be to loop over all the properties of your object with a for .. in loop and count.
You can use the following code. It will produce your desired output 3
var test = {
"ar0":"{\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}",
"ar1":"{\"start\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"end\":{\"lat\":23.0420584,\"lng\":72.67145549999998},\"waypoints\":[[23.02237,72.6500747]]}",
"ar2":"{\"start\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"end\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"waypoints\":[[23.0016629,72.58898380000005]]}"
}
var getLength = function(obj) {
var i = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)){
i++;
}
}
return i;
};
console.log(getLength(test));
For your first question, you should use Object.keys(item).length
To get the values of your object, you should iterate over it with a for loop:
for(var key in item)
{
var val = item[key];
}
var count = 0;
Object.keys(json).forEach(function (key) {
count++;
alert(json[key].start.lat);
});
alert(count);
Using jQuery
$(json).each(function() { count++; alert(this.start.lat); });
alert(count);

Categories

Resources