Unwrap objects in array - javascript

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

Related

Add a key to an object with keys of an existing array with objects

I've got an array of objects array = [object1, object2, ...], each of them has some keys object1 = { key1: 'value1', ... }. I want to add a key this way:
$rootScope.array[i].newKey = 'someValue'
But angular tells me that $rootScope.array[i] is undefined.
What I've noticed from console is that the objects get the new key but the console still says the same.
You should use less than and not less or equal than comparator.
$scope.init = function () {
for (i = 0; i < /* not <= */ $rootScope.meatTypes.length; i++) {
console.log("I am showing the meatypes:");
console.log($rootScope.meatTypes);
$rootScope.meatTypes[i].counter = '0';
counterOperations.setCounters(i, 0);
}
$rootScope.total = 0;
counterOperations.setTopCounter(0);
};
because when i equals $rootScope.meatTypes.length then $rootScope.meatTypes[i] is undefined.
You are trying to access a member of the array that does not exist.
You need to create a new object and push it onto the array:
$rootScope.array.push({'key1': 'someValue'});
You did not mention lodash, but when I see someone encounter an issue like this, I want to offer the recommendation of using lodash (or underscore.js).
With lodash, you would do something like so, using _.set, which defensively protects against your described issue by automatically adding the necessary elements in the path:
_.set($rootScope, ['array', i, 'newKey'], 'someValue');
This library, properly utilized, solves many issues that you can have with setting and getting variables, ase well as other super useful tools. It has been a major life-saver (and time-saver) for us on our projects.
Like this you can add
$rootScope.array[i] = {}; // first we should create an object on that array location
$rootScope.array[i]['newKey'] = 'someValue'; // then only we can add values
EDIT:
$scope.init = function () {
for (i = 0; i <= $rootScope.meatTypes.length; i++) {
console.log("I am showing the meatypes:");
console.log($rootScope.meatTypes);
**// This is needed**
$rootScope.meatTypes[i]={};// here we should tell that metaType[newItem] is an object other wise it treat it as undefined
$rootScope.meatTypes[i].counter = '0';
counterOperations.setCounters(i, 0);
}
$rootScope.total = 0;
counterOperations.setTopCounter(0);
};

Weird behavior of javascript

Please see attached screenshot. See pendingApp property of Object. when I am debugging in eclipse then pendingApp show array of object, Which is correct! But when I am JSON.stringify(object) then showing me empty Array.
Please let me know reason of this behavior. I think I am not aware with any Java-Script thought/concept ?? :P :)
When I will save this Object into DB then blank array of pendingApp will be stored !!
var pending_app = [];
var new_record = {"pendingApp" : [], "installedApp" :[] };
....SOME CODE+conditions HERE....
pending_app[appId] = {'action' : action };
new_record.pendingApp = pending_app;
// create app-config data
return app_model.create(new_record); //will return promise object
It's not a weird behaviour but a common mistake of using an Array to store key-value data.
Short Answer : Use a literal Object to store these data
While you can add properties on every objects in Javascript, you cannot iterate over them with the default array mechanisms
for (var i = 0; i < array.length; i++){}
array.forEach();
Simple demonstration :
var array = [];
array["anId"] = 1;
array.length; // 0
array[4294967295] = 1; // Indice >= unsigned 32-bit Max Value
array.length; // 0
array[4294967295]; // 1
So JSON.stringify with the ECMAScript 5 Specification will use the Array mechanism to iterate over all items and will find nothing.
Unlike Objects that you can list properties with
Object.keys(array); // ["anId"]

Converting JSON not returning Javascript array

I have some JSON returning from my server that looks like this
[{"name1":"value1","name2":"value2"},{"name1":"value1","name2":"value2"},{"name1":"value1","name2":"value2"}]
I then handle this by using
var data = JSON.parse(json);
then, once doing this, I call this in a loop
data.item(i);
or using the function
data.splice(i, 1);
giving me the error
data.item is not a function
or
data.splice is not a function
I'm pretty certain that this is because it is not a true javascript array, but I haven't found anything that has told me how to convert it to one
EDIT I was actually looking for the .item() function used in NodeList (from things like getElementByClassName) however, this does not solve my issue with .splice
Your JSON is invalid - it needs commas separating the objects:
[{"name1":"value1","name2":"value2"},{"name1":"value1","name2":"value2"},{"name1":"value1","name2":"value2"}]
Parse the JSON like you were:
var data = JSON.parse(json);
And to access each object, use the index of the array:
var element1 = data[0]; // first element
var element2 = data[1]; // second element
etc.
And to access the values in the objects:
var name1 = data[0].name1; // value1
or even, since you've already defined the element1 variable:
var name1 = element1.name1;
If you're using a loop:
for (var i = 0, l = arr.length; i < l; i++) {
console.log(data[i]);
}
Once you've run data = JSON.parse(json), you can verify that data is an array using either data instanceof Array or Array.isArray(data).
In this case, both should be true, because you do have an array. JS arrays simply don't have an item method (that is, Array.prototype does not have a property item that is set to a function, or in fact, an item property at all), so you're trying to call something that does not exist.
To access an element from an array, you use the arr[n] syntax with a number. This is how you retrieve elements, not calling item.
While parsing, if your JSON is invalid, an exception will be thrown. You should wrap the JSON.parse call in try { ... } catch block to safely handle that.
All together, your code would look something like:
try {
var data = JSON.parse(json);
if (data && data.length) { // make sure data is a real thing and has some items
for (var i = 0; i < data.length; ++i) {
console.log(data[i]); // using [] to access the element
}
}
} catch (e) {
console.error('Parsing JSON failed:', e);
}

JavaScript Two-Dimensional array is undefined

I was trying to resolve my error with other answers but just fail. I have this simple example of what I think is two-dimensional array but it keeps returning me undefined error.
var city = 'London',
country = 'England';
var locate = [];
locate['London']['England'] = ['Jhon','Mike'];
for (i = 0; i < locate[city][country].length; i++) {
console.log(locate[city][country][i]);
}
jsbin http://jsbin.com/pixeluhojawa/1/
what am I doing wrong in this example, I would appreciate your help.
Before you can assign a value to locate['London']['England'], you'll have to make sure that locate['London'] is an object:
var locate = {};
locate['London'] = {};
locate['London']['England'] = ['Jhon','Mike'];
Notice how I used an object literal ({}) instead of an array literal ([]). Arrays don't support string keys like this. You'll need to use objects instead.
You can also declare it like this::
var locate = {
London:{
England:["Jhon","Mike"]
}
}

Two Dimensional Array in Javascript Object

I want to create an Object that contains one or more two dimensional arrays in Javascript.
I tried it the following way (in this example I only try to add one two dimensional array):
var XSIZE = 8;
var YSIZE = 8;
var obj = {
field : new Array(XSIZE),
field[0] : new Array(YSIZE),
foo : 1,
bar : 100
}
Info:
- This gives me a strange error "missing : after property id" which does not seem to make much sense
- Unfortunately I didn't find examples showing how to do this so far by using google
- If I don't add field[0] ... for creating the 2nd array it works.
- changing the XSIZE and YSIZE to numbers like new Array(8)... doesn't work.
I would really appreciate if somebody could show me how to do it or explain why I cannot do this at all and need to use some other method.
Thanks a lot!
The error "missing : after property id" is because JavaScript sees the field part of field[0] and expects a colon before the value of that field. Instead it gets an open bracket so it complains.
You can't hard code an object definition that has its dimensions set up at run time. You have to build the object at run time as well. Like this perhaps
var XSIZE = 8;
var YSIZE = 8;
var obj = {
field : new Array(),
foo : 1,
bar : 100
}
for (var i = 0; i < XSIZE; i++) {
obj.field.push(new Array(YSIZE));
}
In object literal notation, the property names must be exactly that: property names. Firstly, field[0] isn't a property name. Secondly, the properties don't exist until the after the object defined, so you can't access properties until then.
What you should do is either set the array after the object is created:
var obj = {...}
obj.field[0] = [...];
or nest the array literals:
var obj = {
field: [ [...],
...
],
...
}
You don't need to worry about setting the array size when creating the array, as it will grow when you add elements.
You can only declare properties on the object being constructed that way; not on objects in another "level".
You could use a for loop instead:
for(var i = 0; i < XSIZE; i++) {
obj.field[i] = new Array(YSIZE);
}
Note that the YSIZE is not necessary since an empty array works just fine as well ([]).
You could get the two dimensional array as your obj property, without resorting to external procedures and keep everything internal to the object. Create your empty 'field' array 1st.
var obj = {
field:[],
foo:1,
bar:100
};
Now, create an object's method to create a two dimensional array off your initial dimensionless array. You can determine the length and the number of dimensions of multi dimension array as you wish at run time:
var obj = {
field:[],
multifield:function(x,y){for (var count=0;count<x;count++) {this.field[count]=new Array(y);}},
foo:1,
bar:100
};
You can then call the obj.multifield method entering whatever dimensions you decide:
obj.multifield(10,5); //-->create a 10x5 array in this case...
console.log(obj.field.length); // 10
console.log(obj.field[0].length); // 5

Categories

Resources