JSON/JS- Getting JSON object name - javascript

I have the following object consisting of three other objects of type array :
I want to get the text samsung out of that object and the rest of the objects. I have tried using a for in loop but I am getting the keys 0, 1 , 2.
for(brand in brands){
console.log(brand) // prints out `0, 1 , 2`
}
so I added another nested for in loop, but than I get 0, 0, 0 which are the keys within samsung, and other array objects within the rest of the objects.
What am i missing ?

You can use Object.keys(brands[brand]), and, based on your example, you would want Object.keys(brands[brand])[0]

Your loop is looping through the entire array, rather than the keys of an object.
var brand = brands[0];
for ( var i in brand )
console.log( brand[i] ) // -> samsung
Or to get them all:
for ( var i = 0; i < brands.length; i++){
var brand = brands[i];
for ( var i in brand )
console.log( brand[i] ) // -> samsung
}

You can try
for(brand in brands[0]){
console.log(brand);
}
assuming the name of the array to be brands
EDIT
For all the elements in the array brands
brands.forEach(function(v){
for(brand in v){
console.log(brand);
}
});

Related

How to extract all the values in a specific key in a list of object

i have the list posted below in the code. the list is composed of two keys centerPoint and distanceToTreatment
as shown below i populate the list with some values in a loop and then i sort the list as shown below. what i want to do is, given the list list and the values it contains, i would like to have an array containg only the values in the
key centerPoints
in other words, i would like to have an array containing only the values in centerPoint.so, list contains 50 entry and i would like to have an array contains all the 50 values in the key centerPoint
please let me know how extract all the values contained in a specific key in an array.
code:
let list:Array<{centerPoint:string, distanceToTreatment:number}> = Array()
for(let i = 0; i < this.arrayOfDistancesFromCenterToTreatmen.length;i++) {
list.push({centerPoint: this.arrayOfCenterPointsAsGeoJSON[i], distanceToTreatment:this.arrayOfDistancesFromCenterToTreatmen[i]})
}
list.sort((a,b) => (a.distanceToTreatment > b.distanceToTreatment) ? 1 : ((b.distanceToTreatment > a.distanceToTreatment) ? -1 : 0))
const centerPoints = list.map(l => l.centerPoint);

ng-repeats, showing record while it's value is a part of field of another object

I've got objects 'ing' with a field named 'id' and another one called 'fObj' with a field named 'contain'.
By using ng-repeat i'd like to show only these 'ing' objects where ing.id is a part of fObj.contain
e.g.
ing=[{id: 1,field: value},{id:2, field: othervalue},{id:3, field: cat}];
fObj={field1: value1, field: value2, contain: ':1:3:'};
By having this contain value I'd like to show only ing's with id=1 and id=3
Yeah, I know there are two types of data (number and string) but even if i changed numbers to strings it still didn't work
I just dont't know how to make it works. It's probably some kind of custom filter, but I've tried couples and nothing happend.
I would be glad if you suggest me a solution.
Thanks
In your controller,
var ids = fObj.contain.split(':');
// the array for your ng-repeat
var displayIng = [];
// loop the objects, see if the id exists in the list of id's
// retrieved from the split
for(i = 0; i < ing.length; i++) {
if(ids.indexOf(ing.id.toString()) displayIng.push(ing[i]);
}
I would split the numbers out of fObj.contain; and use them as hashmap object keys for simple filtering of the array
var ing=[{id: 1},{id:2},{id:3}];
var fObj={contain: ':1:3:'};
var IDs = fObj.contain.split(':').reduce(function(a,c){
a[c]=true;
return a;
},{});
// produces {1:true,3:true}
var filtered = ing.filter(function(item){
return IDs[item.id];
});
console.log(filtered)

How to compare a 2-D array and 1-D Array and to Store common Data in Another Array in Java Script

I have 2 Arrays and one is 2 dimensional and another is 1 dimensional. I need to compare both and need to store there common data in another array. I tried the below approach:-
tw.local.listtodisplayNW = new tw.object.listOf.listtodisplayNWBO();
//if(tw.local.SQLResults[0].rows.listLength >
// tw.local.virtualServers.listLength)
var k=0;
for (var i=0;i<tw.local.SQLResults[0].rows.listLength;i++)
{
log.info("Inside SQLResults loop - For RuntimeID: "
+tw.local.SQLResults[0].rows[i].data[3]);
for(var j=0;j<tw.local.virtualServers.listLength;j++)
{
log.info("Inside API loop - For RuntimeID: "
+tw.local.virtualServers[j].runtimeid);
if(tw.local.SQLResults[0].rows[i].data[3] ==
tw.local.virtualServers[j].runtimeid)
{
tw.local.listtodisplayNW[k] = new tw.object.listtodisplayNWBO();
tw.local.listtodisplayNW[k].vsysName =
tw.local.virtualServers[j].virtualSystemName;
tw.local.listtodisplayNW[k].vsysID =
tw.local.virtualServers[j].virtualSystemId;
tw.local.listtodisplayNW[k].serverName =
tw.local.virtualServers[j].serverName;
tw.local.listtodisplayNW[k].serverID =
tw.local.virtualServers[j].serverId;
tw.local.listtodisplayNW[k].runtimeID =
tw.local.virtualServers[j].runtimeid;
//tw.local.listtodisplayNW[k].IPAddress =
tw.local.virtualServers[j].nics[j].ipAddress;
log.info("VsysName:
"+tw.local.listtodisplayNW[k].vsysName+"RuntimeID:
"+tw.local.listtodisplayNW[k].runtimeID);
//tw.local.listtodisplayNW[k] = new
tw.object.listtodisplayNWBO();
tw.local.listtodisplayNW[k].currentSpeed =
tw.local.SQLResults[0].rows[i].data[5];
log.info("VsysName:
"+tw.local.listtodisplayNW[k].vsysName+"RuntimeID:
"+tw.local.listtodisplayNW[k].runtimeID+"CurrentSpeed:
"+tw.local.listtodisplayNW[k].currentSpeed);
if(tw.local.listtodisplayNW[k].currentSpeed != "100 Mbps")
{
tw.local.listtodisplayNW[k].desiredSpeed = "100 Mbps";
}
else
{
tw.local.listtodisplayNW[k].desiredSpeed = "1 Gbps";
}
log.info("DesiredSpeed:
"+tw.local.listtodisplayNW[k].desiredSpeed);
k++;
}
}
log.info("Length of
listtodisplayNW"+tw.local.listtodisplayNW.listLength);
}
In above code SQLResults is a 2-d array and virtualServers is a 1-D array.
I need to compare both these array and common data need to be store in another array. Here performance is not good. Is there any other way to do this efficiently. Please make a needful favour and Thanks in advance.
Assuming integer data, the following example works on the theme of array implementation of set intersection, which will take care of performance.
Convert 2D array to 1D.
var 2DtoIDArray = 2DArray.join().split(",");
Create an array named marker whose purpose is to serve as a lookup that element.
This needs to be done as follows.
Iterate through the smaller array, say 1DArray and keep setting marker as follows throughout iteration.
marker[1DArray[counter]]='S1';
Now iterate through 2Dto1DArray array(you may use nested loop iteration if you dont want to convert it to 1 dimesnional) and for each element
of this array check if its marked as 'S1' in the marker lookup array.
If yes, keep adding the elements in the commonElementsArray.
Follow this simple approach
Since the matching condition is only one between the two large arrays, create two maps (one for each array) to map each record against that attribute which is to be matched
For SQLResults
var map1 = {};
tw.local.SQLResults[0].rows.each( function(row){
map1[ row.data[3] ] = row;
});
and similarly for virtual servers
var map2 = {};
tw.local.virtualServers.each( function(vs){
map2[ vs.runtimeid ] = vs;
});
Now iterate these two maps wrt to their keys and set the values in new array
new array being tw.local.listtodisplayNW
tw.local.listtodisplayNW = [];
Object.keys( map1 ).forEach( function( key ){
if( map2[ key ] )
{
//set the values in tw.local.listtodisplayNW
}
})
Complexity of the approach is simply O(n) since there is no nested loops.

parsing Objects in a loop in javascript

I have a string which I get from an api call and then I parse it into an object using JSON.parse(meetResponse)
meetResponse = {
"returncode":"SUCCESS",
"meetingName":"bbb meeting",
"meetingID":"712",
"createTime":"1457969919738",
"createDate":"Mon Mar 14 11:38:39 EDT 2016",
"voiceBridge":"35014",
"dialNumber":"613-555-1234",
"attendeePW":"PDmAJD4n",
"moderatorPW":"mpassword",
"running":"true",
"duration":"0",
"hasUserJoined":"true",
"recording":"true",
"hasBeenForciblyEnded":"false",
"startTime":"1457969919743",
"endTime":"0","participantCount":"2",
"maxUsers":"20",
"moderatorCount":"2",
"attendees":{
"attendee":[
{
"userID":"10005655",
"fullName":"Snedden Gonsalves",
"role":"MODERATOR",
"customdata":{}
},{
"userID":"10005656",
"fullName":"SneddenReg Gonsalves",
"role":"MODERATOR",
"customdata":{}
}
]
},
"metadata":{},
"messageKey":{},
"message":{}
}
I want to parse 'attendee' under 'attendees' to see who is present
The logic I use right now is :
//check if current user is already present in the meeting
for (var key in meetInfo.attendees.attendee){
console.log('key:',meetInfo.attendees.attendee[key]);
console.log(meetInfo.attendees.attendee[key].userID+"==="+user_id);
if(meetInfo.attendees.attendee[key].userID===user_id){
console.log('in meeting..');
inMeeting=true;
break;
}
else{
inMeeting=false;
}
}
Note:meetInfo is the Whole object
This works is there are more than one attendee but for one attendee it fails.
I am looking for something which would work for any number of 'attendees'.
Also I tried meetInfo.attendees.length instead of Object.keys(meetInfo.attendees).length but it didn't like it
It sounds like your attendees.attendee property could be either an array if multiple, or an object if singular. When it is an array your key variable in the for..in block will be populated the index. When it is an object, it will be populated with the property key.
Two things. First, you can make sure you are always working with an array by concatenating the value with an empty array:
var attendeeList = [].concat(meetInfo.attendees.attendee);
Second, you should not use for..in for iterate through an array. Use a classic for loop instead:
for (var idx= 0; idx < attendeeList.length; idx++)
console.log('key:',attendeeList[idx]);
console.log(attendeeList[idx].userID+"==="+user_id);
if(attendeeList[idx].userID===user_id){
console.log('in meeting..');
inMeeting=true;
break;
} else{
inMeeting=false;
}
}
Bonus, this loop is setting a variable true if any of the items in the array match. There is a special Array function for this:
inMeeting = [].concat(meetInfo.attendees.attendee)
.some(function(a){
return a.userID === user_id;
});

List array into Javascript array?

Goal:
Pass the following tweet to visualization tool and display tweet on the UI.
Setup:
I'm getting the following 'List' on my UI. I just want to convert this list to javascript array (so that I can pass it to Visualization tools). I have concat'd 'qqq' for end of every field to identify where it ends.
Tweet:
[*high-pitched yelp* http://t.co/qaluND2Lu3qqq, neutralqqq, 0qqq,
I checked in at Starbucks on #Yelp http://t.co/8wRVos8STjqqq, negativeqqq, -0.159316qqq,
i would like to thank yelp for not helping me find any club around santa monica that plays progressive edm / progressive tranceqqq, positiveqqq, 0.372338qqq,
Nice long bar table & upstairs option (# Social Kitchen & Brewery) on #Yelp http://t.co/uhQB003NTiqqq, positiveqqq, 0.567625qqq]
Question:
How do I split by 'qqq' and then put it in a javascript array?
I have tried doing the following:
var str = "*high-pitched yelp* http://t.co/qaluND2Lu3qqq, neutralqqq, 0qqq";
var res = str.split("qqq");
But the method adds more one comma (,) at the end of every qqq. I'm confused.
Can someone help?
Update 2
It might be best to just build a new clean array, without any undefined values.
var str = "*high-pitched yelp* http://t.co/qaluND2Lu3qqq, neutralqqq, 0qqq",
myArray = str.split('qqq'),
newArray = new Array();
for ( i = 0; i < myArray.length; i++ ) { // Assuming array is built starting with the key 0
// Denote any array element that is undefined, or nonsensical white-space
if ( myArray[i] !== "" && myArray[i] !== undefined && myArray[i] !== " " ) {
newArray.push(myArray[i]);
}
}
myArray = newArray;
console.log(myArray);

Categories

Resources