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

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

Related

Javascript: Dictionary 'key' value becomes null outside for loop

I have a function which takes a list of dictionaries [{}] as an argument. It manipulates this list of dicts by adding a new key: value pair to it where value is again a list of dictionaries. This is what the function looks like, I've added comments to explain it.
function addFilesToProjects(nonUniqueArray, lists) {
var fileList = [{}]; //this will contain the list of dictionaries that I want to add as a key to the array 'nonUniqueArray'
var filesArray = []; //this was just for testing purposes because I want to access the modified version of nonUniqueArray outside the function, which I'm not able to (it shows undefined for the new key:value pair)
for (var i = 0; i < nonUniqueArray.length; i++) {
lists.forEach(function (list) {
fileNameString = JSON.stringify(list['name']).slice(2, -2);
if (fileNameString.indexOf(nonUniqueArray[i]['title']) !== -1 && fileNameString !== nonUniqueArray[i]['title']) {
fileList.push({
'name': fileNameString
});
}
});
nonUniqueArray[i]['files'] = fileList;
//this logs out the right key:value pair to the console
console.log(nonUniqueArray[i]);
filesArray.push(nonUniqueArray[i]);
while (fileList.length > 0) {
fileList.pop();
}
}
//however, now I get everything as before except the new 'files' key has empty list [] as its value :(
console.log(nonUniqueArray);
return filesArray;
}
I have no clue why is this happening, can someone help?
You seem to think that you are adding a copy of fileList into each dictionary, but in fact are adding the same fileList into each (that is, each is a reference to the same object) so that, as #vlaz points out, when you empty out the original, you are in fact emptying out what appears in each dictionary.

Unwrap objects in array

I have an array of objects:
var Props = [booleanPoint, buttonPoint, checkboxPoint, datePoint, dialPoint, gaugePoint,
groupboxPoint, htmlPoint, imagePoint, livetextPoint, livetrendsPoint, permissionsPoint,
rangePoint, selectPoint, spectrumPoint];
Console log shows:
Edited:
I want to extract the properties inside each object. How do I do it?
To be clear I just want the first property in the array, so that I can do Props.booleanPoint, Props.buttonPoint etc.
You question is not very clear, but I guess you're trying to extract the first (and only) property from each object in the list, whose name you don't know.
If yes, consider this:
extracted = Props.map(function(obj) {
for(var p in obj)
return obj[p];
});
If you want to combine all properties into one big object, try this:
allProps = Object.assign.apply(null, Props)
I'm not sure exactly what result you're after, but the best solution is probably either a forEach or a map.
var properties = {};
Props.forEach(function(object) {
// update properties somehow based on object
});
or
var properties = Props.map(function(object) {
return [some property of object];
});
The first just runs some code on each entry in the array; the second returns a new array with the results of that code.
Otherwise, the classic for loop works too:
var properties = {};
for (var i = 0; i < Props.length; i++ {
// update properties somehow based on Props[i]
}

Accessing properties of a variable object with JavaScript

I have a js object that looks like this:
var object = {
"divisions": {
"ocd-division/country:us": {
"name": "United States",
}
}
};
I want to access the property listed under the nested object "ocd-division/country:us" (aka "name"), but the problem I'm having is that "ocd-division/country" is a variable object. Like it might be ":can" for Canada or something.
My question is, can I still access the name property under that object even though it's variable? I wrote the code I came up with below, but it calls the object literally, so it can't account for a change in the object's name.
var country = document.getElementById("p");
p.innerHTML = object.divisions["ocd-division/country:us"].name;
I'm new to JavaScript so I'm sorry if this is a dumb question.
When you don't know the properties of an object, you can use
for...in loop
It iterates enumerable own and enumerable inherited properties.
Object.keys
It returns an array which contains enumerable own properties.
Object.getOwnPropertyNames
It returns an array which contains own properties.
// Adding properties: "ownEnumerable", "ownNonEnumerable",
// "inheritedEnumerable" and "inheritedNonEnumerable"
var obj = Object.defineProperties({}, {
ownEnumerable: {enumerable: true},
ownNonEnumerable: {},
});
Object.defineProperties(Object.prototype, {
inheritedEnumerable: {enumerable: true},
inheritedNonEnumerable: {},
});
// Display results
function log(id, arr) {
document.getElementById(id).textContent = '[' + arr.join(', ') + ']';
}
log('forin', function(forInProps){
for (var prop in obj) forInProps.push(prop);
return forInProps;
}([]));
log('keys', Object.keys(obj));
log('names', Object.getOwnPropertyNames(obj));
<dl>
<dt><code>for...in</code></dt><dd id="forin"></dd>
<dt><code>Object.keys</code></dt><dd id="keys"></dd>
<dt><code>Object.getOwnPropertyNames</code></dt><dd id="names"></dd>
</dl>
object.divisions[Object.keys(object.divisions)[0]].name
Sure...
for (var division in object.divisions) {
var name = object.divisions[division].name;
// Do what you want with name here
}
If the object has prototype methods you will want to use Object.prototype.hasOwnProperty() to ensure they don't get iterated like so:
for (var division in object.divisions) {
if (!object.divisions.hasOwnProperty(division)) continue;
var name = object.divisions[division].name;
// Do what you want with name here
}
Or use Object.keys() if you don't care about IE8 support and iterate over those.
Object.keys(object.divisions).forEach(function(division) {
var name = object.divisions[division].name;
// Do what you want with name here
});
EDIT: Upon re-reading your question it occurs to me that you may already know the key name but want to access the object with a variable key name, which is also absolutely fine:
var division = 'ocd-division/country:us';
object.divisions[division].name;
When using [] bracket notation to access an object you can insert any code that evaluates to a string, you could even call a function in there that returns a string.
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
You can iterate through object using for loop.
var obj = {
"divisions":{
"ocd-division/country:us":{
"name" : "United States"
}
}
}
Here is the for loop
for(var a in obj){ //loop first the object
for(var b in obj[a]){ // then second object (divisions)
for(var c in obj[a][b]){ //then third object (ocd-division/country:us)
if(c == 'name'){ //c is the key of the object which is name
console.log(obj[a][b][c]); //print in console the value of name which is United States.
obj[a][b][c] = "Canada"; //replace the value of name.
var objName = obj[a][b][c]; //or pass it on variable.
}
}
}
}
console.log(obj); //name: Canada
console.log(objName); //name: United States
You can also use this reference:
https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Statements/for
http://stackoverflow.com/questions/8312459/iterate-through-object-properties

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