JS noob here. I want to store a list of option for a dropdown in an array. I want a key to be associated with every value something like this
var newArray = [
{
key: "key",
val:({value:"val", label:"label"}, {value:"val",label:"label"})
}
]
The code above returns undefined when I try to read val. What is the solution? Thanks
var newArray = [
{
key: "key",
val:[{value:"val", label:"label"}, {value:"val",label:"label"}]
}]
The only thing i changed were parentheses () into [], because it's the thing that declares an array. Now, if you want to read the val key, you need to do this stuff.
You have an array named "newArray". It only has 1 element (which is also the first).
Now lets get the first element of the array by newArray[0]. Now you have accessed the object inside the array. Now you can read the the value by newArray[0].val. And now you have entered a new array, which elements you can read with newArray[0].val[0] and newArray[0].val[1]
Related
I have an object with key value pairs inside an array:
var data = [
{
"errorCode":100,
"message":{},
"name":"InternetGatewayDevice.LANDevice.1.Hosts.HostNumberOfEntries",
"value":"2"
}
];
I want to get the value of "value" key in the object. ie, the output should be "2".
I tried this:
console.log(data[value]);
console.log(data.value);
Both logging "undefined". I saw similar questions in SO itself. But, I couldn't figure out a solution for my problem.
You can use the map property of the array. Never try to get the value by hardcoding the index value, as mentioned in the above answers, Which might get you in trouble. For your case the below code will works.
data.map(x => x.value)
You are trying to get the value from the first element of the array. ie, data[0]. This will work:
console.log(data[0].value);
If you have multiple elements in the array, use JavaScript map function or some other function like forEach to iterate through the arrays.
data.map(x => console.log(x.value));
data.forEach(x => console.log(x.value));
data is Array you need get first element in Array and then get Value property from Object,
var data = [{
"ErrorCode":100,
"Message":{},
"Name":"InternetGatewayDevice.LANDevice.1.Hosts.HostNumberOfEntries",
"Value":"2"
}];
console.log(data[0].Value);
Try this...
Actually Here Data is an array of object so you first need to access that object and then you can access Value of that object.
var data = [
{
"ErrorCode":100,
"Message":{},
"Name":"InternetGatewayDevice.LANDevice.1.Hosts.HostNumberOfEntries",
"Value":"2"
}
];
alert(data[0].Value);
what you are trying to read is an object which an element of an array, so you should first fetch the element of array by specifying its index like
data[0] and then read a property of the fetched object, i.e. .value,
so the complete syntax would be data[0].value
Hope it helps !
I am reading a book called Pro AngularJS by Apress and I am just trying to ensure I understand all of the code and I am a bit baffled by the following code.
Below is a custom filter in the book, which accepts 2 arguments, the data array and a property name. In the book, the property name is the category key in the data, and is set up to remove duplicate categories in order to display a list of navigation links to each category without duplication.
angular.module("customFilters", [])
.filter("unique", function () {
return function (data, propertyName) {
if (angular.isArray(data) && angular.isString(propertyName)) {
var results = [];
var keys = {};
for (var i = 0; i < data.length; i++) {
var val = data[i][propertyName];
if (angular.isUndefined(keys[val])) {
keys[val] = true;
results.push(val);
}
}
return results;
} else {
return data;
}
} });
What I don't understand is the keys part within the for loop. Keys is defined as an object literal?
Then, within the for loop, for each item in the data that us looped over, if the keys[val] is undefined (what does this mean)?
Then keys[val] is set to true (what does this do?).
I sort of understand the rest, if it is undefined, we push the result to the results array to return it.
Thanks for your help :)
Put simply, it's just a way to remember that we already have processed the value val, and do not which to return duplicates, if it comes along again in the loop.
You have to put something in the keys object, like keys[val] = true;, so that keys[val] becomes defined in the next loop iteration.
If you don't put anything into keys[val], angular.isUndefined(keys[val]) in the next loop with same value val will evaluate to true, and then your result would be duplicated (which isn't unique)
Explanation and answer to your questions
if the keys[val] is undefined (what does this mean)?
Basically means the key val doesn't exist in the object keys,
e.g. an object {'age': 45} contains the key age but doesn't contain the key weight
Then keys[val] is set to true (what does this do?)
This sets the key val of the object keys to true, so somewhere keys object looks like this {<val>: true, <other key>: ...,}
So after that step, the key val is defined for the object keys, therefore angular.isUndefined(keys[val]) condition is false
what is the purpose of keys[val] in the first place? Sorry, just not clear on what it is doing.
The code uses an object keys = {} which behaves like a key/value data structure (a dictionary, or a map, in other languages), the goal is to remember that we already have processed val
If you don't remember the values you have already processed (returned), then you will return duplicates, and therefore your unique filter will no longer return unique values, which is the purpose of the code here
Let us see the first line return function(data, propertyName)
here data is the array of objects to be filtered against propertyName(category in this case).
Then we define var keys = {} i.e, an empty object.
Now through for loop we are putting the value of propertyName(category in this case) into variable val.
So for example the first object of data array is like this [{ product: "product 1", category: 'Category 3'}, ....]
Thus the value of val = data[i][propertyName] translates to data[0][category], which evaluates to Category 3.
Now the line angular.isUndefined(keys['Category 3']) would evaluate to true for if condition (here we are asking if the given condition is undefined, which evaluates to true, thus if condition passes).
Within if loop we set the keys[val] = true, so that again this category name is not pushed to the results array.
I am new to constructing a JavaScript Array prototype. Please only paste previous links that are directly appropriate as I have been sourcing on SO and on w3school.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype
I would like to create a method for an array that checks if the 'id' field within the object does not already exist in the array. If not, then 'push' object into the array, else do nothing.
Each object has a unique 'id' field.
eg
var array = [{ id: 001, title: 'some title'},
{ id: 002, title: 'other title'}]
var object = {id: 001, title: 'some title'}
// if object.id does not exist in array...
array.push(object)
//else do nothing
I would like the function to take the 'id' field as an argument so this function has wider use.
Are there any drawbacks to extending the array.Prototype? Otherwise I can do a for loop instead to do the check without the prototype constructor.
Since your ids are integers you could just set that index in the array directly.
var array = [];
var object = {id: 001, title: 'some title'};
array[object.id] = object;
That will overwrite the element in that location such that you won't get duplicates with the same id. Your js engine will automatically switch to using a sparse array rather than a contiguous array if your ids are far apart.
Instead of trying to change the behavior of Array consider using an object instead of array with the id as the key.
var objects = {};
var object = {id: 001, title: 'some title'}
objects[object.id] = object;
That way you can also retrieve your objects from the parent object by their id. e.g.
var result = objects[001];
I found brads's answer using the function containsObject
How do I check if an array includes an object in JavaScript?
This does a check so there is no extra writes to the database such as overwrites. Thank you everyone for inputting towards the question. It has helped.
I want to be able to save an array (if possible), so that I can get to an entry within it quickly and easily with a unique identifier, something like:
array structure:
[
1001:{loads of info},
1002:{loads more info}
]
and to get values like:
var info_i_want = array.1001;
I have the 'loads of info' part already in a json object, just need to built this new array?
I ask because at the moment I have to loop through each object in the array to check if its the one I want before I can do anything
If you want you can use numeric keys with an object literal (not the array notation you used above):
var obj = {
1001: { /* data */},
1002: { /* data */}
};
With numeric keys, you must use bracket notation to dereference; i.e:
obj[1001]; // *not* dot reference `obj.1001` which will not work
Hope this helps :)
EDIT
For reference read the Object section of Javascript Garden, specifically Accessing Properties
you can assume like this.
var arr = [
{1001: "loads of info"},
{1002: "loads more info"}
]
var info_i_want = arr[0].1001 // returns loads of info
I have a JSON object that looks something like this (result from an AJAX call):
json{
code: 0,
resultVal: Object {
data:
[
Object{
generatedName: name1,
generatedValue: value1
},
Object{
generatedName1: name2,
generatedValue1: value2
}....
],
anotherItem: true,
...
}
}
To clarify resultVal is an object and data is an array of objects, and each object in that array will have two values who's names I will not know in advance.
I am having a problem because I need generatedName and generatedValue to be GenerateName and GeneratedValue. These names and values are usually not the as each other. I know can access each Object through json.resultVal.data[#], but that's as far as I have gotten. json.resultVal.data[0].name returns undefined.
Once I can get those values isolated I can make the fixes I need.
NOTE I am running these calls through Chrome's debugger. The thinking is once I am able to isolate the value I can write the code to fix it using that call. It takes some time to get to this point in the application.
Any suggestions?
If I understood it right, you need to iterate over all keys for all objects in "json.resultVal.data". Try using a for/in loop to iterate over the "data" object, as in:
for( var i in json.resultVal.data ) {
for( var k in json.resultVal.data[i] ) {
/* here "k" will be key string ("generatedName", "generatedValue", ...) */
}
}