Access list of Dictionary in Javascript - javascript

I have a list of dictionary items and I want to access them in Javascript. How can I do this?
It is an ajax result and result.d gives the list. (ListItem1, ListItem2, ListItem3)
If I use result.ListItem1[0] I get the value. How can I access the key?

result.ListItem1[0].key or result.ListItem1[0]['key']
Replace "key" with whatever key you are actually wanting to access.

You could enumerate all the properties of your object
var prop, result = {
d: {
ListItem1: ['value1'],
ListItem2: ['value2'],
ListItem3: ['value3']
}
};
for (prop in result.d) {
if (result.d.hasOwnProperty(prop)) {
console.log(result.d[prop]);
}
}
In the log you would then see the 3 array values

Thanks for the response. I used the following to access the Key of the dictionary:
for (t in result.ListItem1)
{
type = result.ListItem1[t];
typeId = t;
alert(t);
o.push('<option value="');
o.push(t);
o.push('" class="chz-option">');
o.push(type);
o.push('</option>');
}
$('#type').html(o.join(''));

Related

How to filter the dynamic Json data using underscore.js?

I have an array of json objects with dynamic data in it i.e both the keys and values are dynamic as :
arr=[{"a":"email"},{"b":"chat"},{"c":"email"},{"d":"chat"},{"e":"email"}]
The size of arr may change i.e it may have any number of json objects.
How do I filter the data using underscore.js ??
This is what I was trying to do :
filterData(searchValue:string){
this.skillGrpsFilteredData= _.filter(this.skillGroupsAndTypes, function(obj) {
return ~obj.toLowerCase().includes(searchValue) as any;
});
}
But this approach is not working as the keys in the above array obj is dynamic i.e "a,b,c,d,e,.." are dynamic in nature.
And searchValue is the value that comes from the frontend UI.
How do I perform search using keys i.e if I type searchValue=a it should give me that object and so on .
Thanks & Regards
Try the following function. In the array parameter you can pass arr=[{"a":"email"},{"b":"chat"},{"c":"email"},{"d":"chat"},{"e":"email"}] and in searchKey parameter pass such as "a" it will return {"a":"email"}. If match not found function will return null
searchByKey(array,searchKey ) {
for (let obj of array) {
for (let key in obj) {
if (key == searchKey) {
return obj;
}
}
}
return null;
}
Try this
Following function filters array objects containing the search value both in key and value of the object
in your case you can pass 'a' or "email" to get the objects
function searchObject(array , searchValue){
return array.filter(item=>{ return Object.keys(item).includes(searchValue) ||Object.values(item).includes(searchValue)})
}
let arr=[{"a":"email"},{"b":"chat"},{"c":"email"},{"d":"chat"},{"e":"email"}]
console.log(searchObject(arr,'a'));
if you want just to filter by key and not by value of the object remove the
Object.values(item).includes(searchValue)
from the or condition
if you want to try indexOf
try
function searchObject(array , searchValue){
return array.filter(item=>{ return
Object.keys(item).indexOf(searchValue)>=0})
}

Object.getOwnPropertyNames Function (JavaScript) from this data it does'nt work

i am having trouble to get object property name from this data that i retrieve from some API server :
var arrData = [{"data":
{"plmn":"Voda","id":"B193","time":1499257121817,"cell":{"rsrp":
[-132.5,-108.88],"rsrq":[-18.69,-6.56],"earfcn":1550,"pci":454,"celltiming":
[252],"sinr":-12.8,10.7]},"mac":"9C65F9"},"time":1499282331405,
},{"data":
{"plmn":"Voda","rssi":-106,"id":"4179","time":315939662698,"cells":
[{"sc":453,"ecno":-19.53,"r99":"intraMon","rscp":-125.53,"ch":10837},
{"sc":452,"ecno":-13.97,"r99":"active","rscp":-119.97,"ch":10837},
{"sc":452,"ecno":-19.53,"r99":"active","rscp":-125.53,"ch":10812},
{"sc":453,"ecno":-19.37,"r99":"intra","rscp":-125.37,"ch":10812}],"mac":
"9C65F9211012"},"time":1499282452590,"deviceID":"9C65F9211012"}]
i already try with this code :
var collectField = [];
for (var prop in arrData) {
if (arrData.hasOwnProperty(prop)) {
collectField.push(prop);
}
}
// and still wrong Outputs: [0,1,2,3.....]
console.log(collectField);
the output result that i expected :
[plmn,id,time,cell,,ecno,cells,rscp..and all of that object field]
hope someone can help this problem.
Thanks in advance
for-in construct doesn't retrieve the object from array but it's index. So you're trying to access hasOwnProperty on the number. First you need to access array member and then property eg. like this:
for (var index in arrData) {
var obj = arrData[index];
if (obj.hasOwnProperty(prop)) {
collectField.push(obj[prop]);
}
}

Search value in object

I have following object im not sure how to proceed.
Object image
How can I go through all objects and select the content array and search for a value x. And when the value x is in the object I need to get the object title from the object where the value was found.
Can anyone give me a hint how I can solve this problem?
you can use for...in to iterate over the object and indexOf() to check if a key exists in the array content. something like this:
function searchVal(x){
for(var key in obj){
if(obj[key].hasOwnProperty('content') && obj[key].content.includes(x))
return key;
}
}
You can use for...in to iterate the object keys, then a regular for loop to check the content array for your specific value:
function findTitle(x) {
for (var key in obj) {
for (var i = 0; i < obj[key].content.length; i++) {
if (obj[key].content[i] === x) {
return key;
}
}
}
}
let name = Object.values( obj /*your main object*/ )
.find( obj => obj.content.includes(x) )
.name;
You could find the first object in the Objects values of your main obj, that has a property content which includes x, then get the name of that object.

Find index of object in array by key

I have an array of objects like so
myobj= [{"item1" : info in here},{"item2" : info in here}, {"item3" : info in here}]
I'm trying to modify one, but I only know its key. I need to pinpoint the item1 object so I can change its value (the values are random and I don't know them, so I can't rely upon them).
If I could just get the index of the item it would be pretty easy: myobj[index].value = "newvalue".
Maybe using the index isn't the best way, so if it isn't, I'm open to other ideas.
I was thinking I could try something like
myobj.objectVar
Where objectVar is the key I'm being passed (item1, for example), however this does not work, possibly because it's a variable? Is it possible to use a variable like this maybe?
If it helps, I'm using underscore.js as well.
Your guess at a solution doesn't work because you're not accessing the individual objects, you're accessing an array of objects, each of which has a single property.
To use the data in the format you've got now, you need to iterate over the outer array until you find the object that contains the key you're after, and then modify its value.
myobj= [{"item1" : info in here},{"item2" : info in here}, {"item3" : info in here}]
function setByKey(key, value) {
myObj.forEach(function (obj) {
// only works if your object's values are truthy
if (obj[key]) {
obj[key] = value;
}
});
}
setByKey('item1', 'new value');
Of course, the far better solution is to stop using an array of single-property objects, and just use one object with multiple properties:
myobj= {"item1" : info in here, "item2" : info in here, "item3" : info in here};
Now, you can simply use myObject.item1 = "some new value" and it will work fine.
You can write a function like,
function getElementsHavingKey(key) {
var objectsHavingGivenKey = [];
//loop through all the objects in the array 'myobj'
myobj.forEach(function(individualObject) {
//you can use 'hasOwnProperty' method to find whether the provided key
// is present in the object or not
if(individualObject.hasOwnProperty(key)) {
// if the key is present, store the object having the key
// into the array (many objects may have same key in it)
objectsHavingGivenKey.push(individualObject);
}
});
// return the array containing the objects having the keys
return objectsHavingGivenKey;
}
If you only want to get the index of elements having the given key
You can do something like this,
function getIndexesOfElementsHavingKey(key) {
var objectsHavingGivenKey = [];
//loop through all the objects in the array 'myobj'
myobj.forEach(function(individualObject, index) {
//you can use 'hasOwnProperty' method to find whether the provided key
// is present in the object or not
if(individualObject.hasOwnProperty(key)) {
//push index of element which has the key
objectsHavingGivenKey.push(index);
}
});
// returns the array of element indexes which has the key
return objectsHavingGivenKey;
}
Try this code:
function changeObj( obj, key, newval )
{
for( var i=0, l=obj.length; i<j; i++)
{
if( key in obj[i] )
{
obj[i] = newval;
return;
}
}
}
var myObjArray= [{"item1" : "info in here"},{"item2" : "info in here"}, {"item3" : "info in here"}]
To find and add new value to the object inside an array:
myObjArray.forEach(function(obj) {
for(var key in obj) {
// in case you're matching key & value
if(key === "item1") {
obj[key] = "update value";
// you can even set new property as well
obj.newkey = "New value";
}
}
});
You can access objects the same using their index, even the object inside the original object.
Is this kind of what your looking for:
var otherObj = [{"oitem":"oValue"}];
var myobj= [{"item1" : otherObj},{"item2" : "2"}, {"item3" : "tesT"}];
myobj[0].item1[0].oitem = "newvalue";
alert(myobj[0].item1[0].oitem);

How to implement such an associative array?

arr[key] = value;
where key is a jQuery object and value is an array.
Associative arrays don't really exist in JavaScript. However, you can achieve similar functionality using JavaScript objects:
// Create object
var myObject = {
key: value,
helloText: "Hello World!"
};
// Access object in some statement via:
myObject.helloText
// ...or:
myObject["helloText"]
To use an object as a key, you would have to do something like:
var a = {
helloText: "Hello World!"
};
var b = {};
b[a] = "Testing";
alert(b[a]); // Returns "Testing" (at least, in Safari 4.0.4)
Using an object as a key sounds a bit weird, though. Are you sure you need to do this?
Update:
You can't actually use an object as a key in JavaScript. The reason the above code appears to work is that, in the statement b[a] = "Testing";, JavaScript converts a to a string via a.toString(), which results in "[object Object]", and uses this string as the key. So our statement is actually b["[object Object]"] = "Testing"; and our alert statement is exactly the same as alert(b["[object Object]"]);.
Thanks to CMS for pointing this out in the comments!
Update 2:
Tim Down points out that his JavaScript library jshashtable allows you use an object as a key.
You can use jshashtable, which allows any JavaScript object as a key.
Just guessing here, but it seems you're trying to associate some (arbitrary) data with a jQuery object (possibly an element). In that case, why not use the data () method?
$('#el').data (value);
You can't use objects as keys, and assocative arrays are not what they seem in Javascript because all you're doing is setting a property on the array object, when you loop through by the .length it natively doesn't account for the manually defined properties you set.
I suggest storing the elements and arrays inside of object literals, all inside of an array. Eg:
var list = [
{
el:document.body,
arr:[1,2]
}
];
for ( var i = 0, l = list.length; i<l; ++i ) {
alert( list[i]['el'] )
alert( list[i]['arr'][0] )
}
// add elements to the array
list.push({
el:document.body.firstChild,
arr:[3,4]
})
As kprime mentioned in his answer though, it might be better to use .data() if you are using Javascript.
if ( !$(el).data('key') ) {
$(el).data('key', [2,3,4] );
}
I would suggest assigning a unique ID to each element you want to put in the associative container (object in JS) and use the ID as key:
var idCounter = 0;
var container = { };
function storeValue(element, value) {
if (!element.getAttribute('id')) {
element.setAttribute('id', makeID());
}
var id = element.getAttribute('id');
container[id] = value;
}
function makeID() {
return 'unique-id-' + idCounter++;
}
EDIT: This solution assumes that jQuery is not available. If it is, use data('key', value).
every javascript object is an associative array, this is a property build in the language, you do not need to anything special, just use it like that

Categories

Resources