extract data of interest from array object - javascript

i am trying to extract specific data from an array object using keys but all the data gets returned? why is that? i want to print to the console all the values corresponding to the key genestart only
for (var i=0; i<genedata.matches.length;i++){
var arr = genedata.matches[i];
for (var key in arr){
var attrName=key;
var attrValue = arr[key];
//console.log(attrValue);
if (attrName='genestart'){
console.log(attrValue);
}
}
}

Your if statement is not a comparison but an assignment. Change = to ==

Related

How to check if a value exists in json array? If match is found, delete the key value pair

I have a sharepoint column named AllLinks in which im storing array as:
[{"AllLinks":"Link9","LinkURL":"http://www.Link9.com"},
{"AllLinks":"Link6","LinkURL":"http://www.Link6.com"}]
How to check if a value exists in an array of objects and if a match is found, delete the key value pair.
For example if the value Link6 matches, delete the entry completely from the array using javascript/jquery. I tried with:
var newA = data.d.results.filter(function (item) return item.AllLinks !== x;});
but item.AllLinks again returns the complete array itself
as AllLinks is a column in my sharepoint list.
You can use filter function:
var a = [{"AllLinks":"Link9","LinkURL":"http://www.Link9.com"},{"AllLinks":"Link6","LinkURL":"http://www.Link6.com"}]
var newA = a.filter(function (item) {
return item.AllLinks !== "Link6";
});
You can do this in such an easy way here:
var jsonArry = [{"AllLinks":"Link9","LinkURL":"http://www.Link9.com"},{"AllLinks":"Link6","LinkURL":"http://www.Link6.com"}];
var value = "Link6";
for(var i=0; i<jsonArry.length; i++){
if(jsonArry[i].AllLinks === value){
jsonArry.splice(i,1);
}
}
console.log(JSON.stringify(jsonArry));
If you are sure that the value key is unique then add a break keyword inside the for loop within if after you delete the object so as to prevent unnecessary loops like this,
for(var i=0; i<jsonArry.length; i++){
if(jsonArry[i].AllLinks === value){
jsonArry.splice(i,1);
break;
}
}

How to sort the order of the nested array object using javascript/jquery

Having a nested array object, trying to sort it based on the order value present in my object.
So, am splitting the object and pushing it into two new array variables.
But in one of my object response there is an array, i need to sort the values in ascending order. Here it is what I have tried.
JS:
var obj = {details:[{type:"general",order:1,},{type:"general1",order:3,},{type:"static",order:4,list:[{type:"static2",order:3,},{type:"static1",order:2,},]},{type:"general2",order:2,}]};
var basicArray = [];
var listArray = [];
var sortedArray = "";
var sortedListArray = "";
var checkListArray = [];
var objDetails = obj.details;
sortedArray = _.sortBy(objDetails,"order");
for(var i=0;i<sortedArray.length;i++){
if(sortedArray[i].list){
listArray.push(sortedArray[i]);
}
else{
basicArray.push(sortedArray[i]);
}
}
for(var j=0;j<listArray.length;j++){
if(listArray[j].list){
for(var k=0;k<listArray[j].list.length;k++){
sortedListArray = _.sortBy(listArray[k].list,"order");
checkListArray.push(listArray[k].list);
}
}
}
Demo URL
So the expected output is in my second loop, i want to order the values of my array, like I did in my first loop
Use sortBy on list :
for(var i=0;i<sortedArray.length;i++){
if(sortedArray[i].list){
sortedArray[i].list =_.sortBy(sortedArray[i].list,"order");
checkListArray.push(sortedArray[i].list); // add sorted list to checklist
basicArray.push(sortedArray[i]); // add element with sorted list to basic array
}
else{
basicArray.push(sortedArray[i]);
}
}

Get data and make changes on javascript object

I have an object.
But i don't know how to get the ID because it change for each page.
So if make:
var obj = bundle.config.options
I get this result:
http://imgur.com/hWcAR83
Then, i want to get in a var the number of the object -> '42' in this case
And then, i want to insert into the selection, and i hope it was like:
bundle.config.options[42].selections[314]
And then change the fields.
Am i confused?
How could get this value?
UPDATE
I have associate by loop of other objets, the minQty of products for each product.
$minimumQty = $_selection->getStockItem()->getMinSaleQty();
echo("<script>
var obj = bundle.config.options ;
var a = Object.keys(obj);
var keys = [];
for(var k in obj[a].selections) keys.push(k);
obj[a].selections[keys[d]].minQty = ".$minimumQty."
</script><br>");
The result -> each selection have the field: minQty with their number.
Try using Object.keys(obj), here is a link on how it is used.
OR
You can loop through you Object and get the keys
var keys = [];
for(var k in obj) keys.push(k);

How to convert Javascript array to JSON string

I have an array called values which has this data
var values=new Array();
values.push("english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav");
values.push("kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav");
When I do JSON.stringify(values) I get values with square brackets, but I need a JSON string a shown below with urllist appended at the first.
{
"urlList":{
"english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav",
"kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav"
}
}
Your code as you've defined it will give you errors. This is not valid JavaScript; you can't create an array element like this.
values.push("english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav");
If you want the structure you've specified in your question then you'll need to use a nested object rather than an array to contain the key/value pairs.
var values = {
urlList: {}
};
values.urllist.english = "http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav";
values.urllist.kannada = "http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav";
DEMO
HOWEVER...
Let's assume for a moment that what you meant to code was this (note the curly braces):
var values=new Array();
values.push({"english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav"});
values.push({"kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav"});
This would tell me that you're pushing objects into an array which is perfectly valid JavaScript.
To get this information from the array into the structure you need you can use something like this loop:
var out = {
urlList: {}
};
for (var i = 0, l = values.length; i < l; i++) {
var el = values[i];
var key = Object.keys(el);
var value = el[key];
out.urlList[key] = value;
}
JSON.stringify(out);
DEMO

JSON parsing in Javascript with no known number of items

I'm drawing a blank with the best way to process JSON data which will be of the following form:
[{"latlng":"42.6674996,-71.1786423"},
{"latlng":"53.8136722,-1.7301123"}]
var p = '[{"latlng":"42.6674996,-71.1786423"},
{"latlng":"53.8136722,-1.7301123"}]',
It will also be of variable length.
I'm having trouble looking through all the data pairs pulling off the latlng values.
I'm using the code:
for (var key in p) {
if (p.hasOwnProperty(key)) {
alert(key + " -> " + p[key]);
}
}
from this other SO question: How do I loop through or enumerate a JavaScript object?
However, the formats in the above example are different from mine.
How do I loop through each key/value in turn until the JSON string is exhausted?
I'm a little new to JSON and Javascript.
You can always use JSON.parse (on any remotely modern browser) to take a json string and get the relevant javascript structure. Once you have that, you can iterate over the structure.
So you start with
var json = '[{"latlng":"42.6674996,-71.1786423"}, {"latlng":"53.8136722,-1.7301123"}]';
and then you can get a javascript array by
var ary = JSON.parse(json);
From here you are just a hop skip and jump away from iterating over your array, getting the current element, and doing what you want.
Note for your structure, instead of returning
{"latlng":"42.6674996,-71.1786423"}
for each element in the array, you should do
{"lat":"42.6674996","long": "-71.1786423"}
that way as you iterate over the array, you can do something like
...in your for loop
var current = ary[i];
var lat = current.lat;
var long = current.long;
Use the jQuery.parseJSON - jQuery API:
var json = '[{"latlng":"42.6674996,-71.1786423"},{"latlng":"53.8136722,-1.7301123"}]';
var parsed = $.parseJSON(json);
$.each(parsed, function(index, value) {
console.log(value['latlng']);
});
or the native JSON.parse:
var json = '[{"latlng":"42.6674996,-71.1786423"},{"latlng":"53.8136722,-1.7301123"}]';
var parsed = JSON.parse(json);
var count = parsed.length;
for (var i = 0; i < length; i++)
console.log(parsed[i]['latlng']);
You're going to have to turn that string into an object before you can iterate through it safely:
var p = JSON.parse('[{"latlng":"42.6674996,-71.1786423"}, {"latlng":"53.8136722,-1.7301123"}]');
for(key = 0; key < p.length; key++) { // Start the key at zero, increment until it his the object's length
if (p.hasOwnProperty(key)) { // If the item has a key
alert(key + " -> " + p[key]); // Alert the key and then the item.
}
}
In your case, you have a multidimensional object. So each return will give you another object. How I would deal with this is by traversing the returned object like so:
alert(p[key]['latlng']);
To have a better understanding of this, look at the initial object syntax...
[
{ // key 0
"latlng": "42.68, -71.18" // key 'latlng'
},
{ // key 1
"latlng": "53.81, -1.73" // key 'latlng'
}
]
So essentially you're traversing the object using the values that the loop increments. If you have an object with 5 items your loop will grab that number and cycle through 5 times (0 .. 4). Each time it loops the incremented key variable will be used to select your item, and from there you can grab the the latlng key and return its value within the nested object.

Categories

Resources