how to read data from an object javascript - javascript

i have an object evt.participators that contains objects. when loggin it , i show this result:
I want to read all the id of evt.participators objects. I try this code :
var t=0 ;
angular.forEach(evt.participators, function(value, key){
console.log(evt.participators.$id );
t++;
});
But i get three time undefined.
How can i fix it please ?

You can easily retrieve all the keys in the object by using a for...in loop
for (var key in evt.participators) {
if (evt.participators.hasOwnProperty(key)) {
console.log(key);
}
}
JsFiddle: https://jsfiddle.net/er647anm/1/

use for..in for loop through object
for (var prop in evt.participators) {
console.log(evt.participators[prop]);
}
for more information please follow For..In Documentation

Related

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.

Iterate over a List object in Javascript

How can I iterate over a List object in Javascript? It contain more than 1 value.
List <controllerclass> obj = dao.listimpl();
I tried this:
for (index = 0; index < obj .length; ++index) {
console.log(obj [index]);
}
Looping using Iterators in Javascript is new to ES6 and explained below.
MDN Iterators and generators - Explains that, in Javascript, an iterator is a data object that just has a next() method. The result returned from Iterator.next() has a next() method, done and value properties. An example is shown below using the Javascript Set object.
let aCollection = new Set(['item1', 'item2', 'item3']);
let it = aCollection[Symbol.iterator]();
console.log('iterator is', it)
console.log('it.done - is not meaningful', it.done); // notice that it.done is not defined!
let itLoop = it.next()
console.log('it.next()', itLoop);
console.log('it.next().value', itLoop.value);
console.log('it.next().done', itLoop.done);
Output of the above sample code is:
iterator is SetIterator { 'item1', 'item2', 'item3' }
it.done - is not meaningful undefined
it.next() { value: 'item1', done: false }
it.next().value item1
it.next().done false
Set.prototype##iterator - Explains how to use a Set iterator. What puzzled me is why examples didn't include looping so I provide examples below.
Using for...of
The easiest way to loop using an iterator is using the for(item of collection) syntax as described here in MDN. A more complete description of looping is covered very well here.
for(let item of aCollection){
console.log('for...of returns ', item);
}
Using for(;;)
Next is a for loop using an iterator.
for(let it = aCollection[Symbol.iterator](), loop = it.next(); ! loop.done; loop = it.next()){
console.log('for(;;) ', loop.value);
}
Using while loop
And next is a while loop using an iterator:
let it = aCollection[Symbol.iterator]();
let loop = it.next();
while (! loop.done){
console.log('while loop ', loop.value);
loop = it.next();
}
Hopefully this helps someone. The full runable example is at https://jsfiddle.net/PatS2265/y5a4hvb7/4/. There is no HTML or CSS, just Javascript console.log output, so open a browser console window see the output.
First of all List <controllerclass> obj = dao.listimpl();this is java code you have pasted, try to paste the exact object which you trying to iterate.
Though i would recommend use a very lightweight javascript library Loadash which is very handy, when you are dealing with array/objects and looping through these items and many more util methods.
_.forOwn(obj, function(value, key) { } );
Loadash - forOwn
Iterates over own enumerable string keyed properties of an object and invokes iteratee for each property. The iteratee is invoked with three arguments: (value, key, object). Iteratee functions may exit iteration early by explicitly returning false
Object does not have length property like array.
Please use the following code to iterate
for (var key in obj) {
if (obj.hasOwnProperty(key)){
alert("property "+key+ " is " + obj[key] );
}
}
Hope this solves your problem.

Access list of Dictionary in 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(''));

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

Categories

Resources