How can I retrive a value from this json object? - javascript

<script>
var output = {"regions":{"4441":"Avtonomna Respublika Krym","4431":"Cherkas'ka Oblast'","4432":"Chernihivs'ka Oblast'","4433":"Chernivets'ka Oblast'","4434":"Dnipropetrovs'ka Oblast'","4435":"Donets'ka Oblast'","4436":"Ivano-Frankivs'ka Oblast'","4437":"Kharkivs'ka Oblast'","4438":"Khersons'ka Oblast'","4439":"Khmel'nyts'ka Oblast'","4440":"Kirovohrads'ka Oblast'","4443":"Kyyivs'ka Oblast'","4445":"L'vivs'ka Oblast'","4444":"Luhans'ka Oblast'","4442":"Misto Kyyiv","4450":"Misto Sevastopol","4446":"Mykolayivs'ka Oblast'","4447":"Odes'ka Oblast","4448":"Poltavs'ka Oblast'","4449":"Rivnens'ka Oblast'","4451":"Sums'ka Oblast'","4452":"Ternopil's'ka Oblast'","788":"Ukraine","4453":"Vinnyts'ka Oblast'","4454":"Volyns'ka Oblast'","4455":"Zakarpats'ka Oblast'","4456":"Zaporiz'ka Oblast'","4457":"Zhytomyrs'ka Oblast'"}}
alert(output.regions[1]);
</script>
This part gives me undefined:
alert(output.regions[1]);
How can I grab the first key/value pair for example. Basically I need to turn this into a select dropdown, the numeric keys would be the values and the names of the cities would be the option text.

Can iterate over it like:
for(key in output.regions) {
alert(key +' => '+output.regions[key]); // 4441 => Avtonomna Respublika Krym ...etc
}

Rather than a numeric index, you'll want to key into regions with the keys you've specified, like 4441, 4431, etc:
var output = {"regions":{"4441":"Avtonomna Respublika Krym","4431":"Cherkas'ka Oblast'","4432":"Chernihivs'ka Oblast'","4433":"Chernivets'ka Oblast'","4434":"Dnipropetrovs'ka Oblast'","4435":"Donets'ka Oblast'","4436":"Ivano-Frankivs'ka Oblast'","4437":"Kharkivs'ka Oblast'","4438":"Khersons'ka Oblast'","4439":"Khmel'nyts'ka Oblast'","4440":"Kirovohrads'ka Oblast'","4443":"Kyyivs'ka Oblast'","4445":"L'vivs'ka Oblast'","4444":"Luhans'ka Oblast'","4442":"Misto Kyyiv","4450":"Misto Sevastopol","4446":"Mykolayivs'ka Oblast'","4447":"Odes'ka Oblast","4448":"Poltavs'ka Oblast'","4449":"Rivnens'ka Oblast'","4451":"Sums'ka Oblast'","4452":"Ternopil's'ka Oblast'","788":"Ukraine","4453":"Vinnyts'ka Oblast'","4454":"Volyns'ka Oblast'","4455":"Zakarpats'ka Oblast'","4456":"Zaporiz'ka Oblast'","4457":"Zhytomyrs'ka Oblast'"}}
alert(output.regions[4441]); // alerts "Avtonomna Respublika Krym"

The regions entity is an object and not an array so you have to select its attribute by its associated key.
output.regions.4441
or
output.regions['4441']

The value with the key "regions" is a map, not an array - it has no ordering, therefore there is no concept of "first key/value pair" - you'll have to impose your own ordering if you want one.

This is because output.regions is an object, not an array. You would either need to access by the ID (778) or if you don't know it, than you can iterate to find it.
for (k in output.regions) { var key = k; break; }
alert(output.regions[key]);

There is no "first" value. Properties of javascript objects are not ordered. You can iterate over a javascript object like this:
for(key in output.regions){
alert(output.regions[key])
}
and check for the cycle of iteration, but there's no guarantee that the order won't change unexpectedly. To have a guaranteed order, you need to use an array.

Related

JavaScript - Maintain Object key value order

My required object key-value(property-value) Order : {three:3,two:2,one:1}
I want last added key at top,When i add key-value dynamically the order i got is given below,
var numObj={};
numObj["one"]=1;
numObj["two"]=2;
numObj["three"]=3;
console.log(numObj) // result i get is { one:1, three:3,two:2 }
Please any one help me to get this key-value order {three:3,two:2,one:1}
As the commenters point out, JavaScript objects have no defined order for iteration. However, JavaScript maps do: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map.
let aMap = new Map();
myMap.set('AKey1', 'AValue1');
myMap.set('AKey2', 'AValue2');
myMap.set('AKey3', 'AValue3');
for (let x of aMap) {
console.log(x[1]);
}
Will provide
AValue1
AValue2
AValue3

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)

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;
});

fetch data from nested JSON object in a single line

This is my JSON data ....
{"comp1":["$.Create_Keypair1_Keypair_name"]}
I want to get the value "Create_Keypair1_Keypair_name".but all the keys and values are dynamic.but the object always have single data.
I have Object.keys(temp).It shows only ["comp1"] i need
$.Create_Keypair1_Keypair_name only....
Try this:
var data = {"comp1":["$.Create_Keypair1_Keypair_name"]}
for (var key in data) {
console.log(data[key])
}
This will log $.Create_Keypair1_Keypair_name.
From what I am understanding each object will have a single value. If the is the case then you do not need the array in the object. You can do this.
var tempy = {"comp":"ksmdfnsfdnsdfn"}
Then do this to ge the value.
tempy.comp
Or if you need the keys.
Object.keys(tempy)
you might be looking for this
var temp = {"comp1":["$.Create_Keypair1_Keypair_name"]}
Object.keys(temp).forEach(function(key){
console.log(temp[key]);
});

JS and ExpressionEngine - Remove KV pairs by duplicate values only?

We're building a site with ExpressionEngine. We are running a SQL query to gather up all member IDs for a specific member group. After that, we are using EE tags to get data from a custom member field for each member ID.
The ID and field data need to stay paired, as we will be populating a drop-down so that the ID is the value and the field data is the text, so we are currently putting them into a JS array as key/value pairs. The call is as follows:
var array= [
{exp:query sql="SELECT * FROM exp_members WHERE group_id = 5"}
{exp:member:custom_profile_data
member_id="{member_id}"}
{if company != ''}
{{member_id}:"{company}"},
{/if}
{/exp:member:custom_profile_data}
{/exp:query}
};
This gives us the output:
var array = [
{1:"name01"},
{2:"name02"},
{3:"name01"},
{4:"name03"}
];
Now, our problem. We need to remove objects based on duplicate field data (values) only, so the above array would look like this:
var array = [
{1:"name01"},
{2:"name02"},
{4:"name03"}
];
None of these IDs (keys) will ever be the same, but the field data (values) can be. So we want to keep the first KV pair that comes through with a unique value, but remove any subsequent dupes of that value - despite the fact that they will not be true "duplicate values" due to a different ID (key).
Keeping in mind that the KV pairs are all dynamic, is there any possible way to do this via JS so we can create a new array for the cleaned data to pass to the drop-down?
You could handle the duplications by modifying your MySQL query. (In my example, my custom field ID was 1.)
var myArray = [];
{exp:query sql="SELECT MIN(m.member_id) AS co_member_id, d.m_field_id_1 AS company FROM exp_members m INNER JOIN exp_member_data d ON m.member_id = d.member_id WHERE d.m_field_id_1 != '' AND m.group_id > 0 GROUP BY d.m_field_id_1;"}
myArray.push({{co_member_id}: "{company}"});
{/exp:query}
This query would use the first (in the ordinal sense) member_id found; you could also change the MIN to MAX and get the last.
This will give you a clean output in your source, without the need for any additional JS processing. I'd also recommend changing the names of the variables you're outputting as to not conflict in EE's parsing.
I would do it like...
function removeDups(arry){
var tmp = {}, retainIdx=[], newArry=[];
arry.forEach(function(obj, idx){
var val = obj[Object.keys(obj)[0]];
if(val && !tmp[val]){
retainIdx.push(idx);
tmp[val] = true;
}
});
retainIdx.forEach(function(i){
newArry.push(arry[i]);
});
return newArry;
};

Categories

Resources