I'm having trouble understanding the way this for in loop works.
function createSimpleNode(name, options, text) {
var node = document.createElement(name);
for (var o in options) {
node.setAttribute(o, options[o]);
}
if (text) {
node.innerHTML = text;
}
return node;
}
The For in loop gives a way to iterate over an object or array with each value and key.
It can be applied over an object or Array.
For an Object
For an object it gives each key in the object as the ITER variable. Using this variable you can get the corresponding value from object.
var options = {a:1,b:2};
for (var key in options) {
console.log(o,options[key]);
}
Will Iterate over the options object and print each key and it's value.
a 1 //first key is a and options["a"] is 1
b 2 //first key is a and options["b"] is 2
For an Array
For an array it gives each index in the array as the ITER variable. Using this variable you can get the corresponding element from array.
var options = ["a","b"];
for (var index in options) {
console.log(index,options[index]);
}
Will Iterate over the options array and print each index and element on given index. Output will be:-
0 a //first index is a and options[0] is a
1 b //second index is a and options[1] is b
This is a for..in loop. it iterates over the properties of an object (options, in this case), and allows you access the said property in each iteration using the [] operator.
In your example, you iterate over options properties, and set them all as attributes of node.
Related
I need to access the 2.2.10.60 and "bank overdrafts...." value from the following array --
May I ask about how to get it?
Here with my code.
var json=chunk.toString();
var obj = JSON.parse(json);
session.send(obj.clauses[0]);
console.log(obj.clauses[0]);
But I can't get the value of "2.3.10.60" and "Bank overdrafts....".
and the inside the "clauses" array will always change.
I had Solved by my own:
var graph = JSON.parse(json);
for(var i=0;i<graph.clauses.length;i++){
var obj=graph.clauses[i];
console.log(obj);
var clause_id;
var clause_text;
for(var key in obj)
{
clause_id=key;
clause_text=obj[key].toString();
session.send(clause_id+"<br>"+clause_text);
}
}
You could use Array#find and check if the wanted property exist in the object. Then take the object and use an property accessor for the result.
key = '2.2.10.60'
result = clauses.find(object => key in object)[key];
If you are not sure about if the array does not contain any object with this key, take an default object or check in advance if find returns a truthy value (like an object), take this
var key = '2.2.10.60'
result,
temp = clauses.find(object => key in object);
if (temp) {
result = temp[key];
}
For a dynamic approach, you could take a variable for the wanted key.
For getting just the first entry of the object, you could take the entries of index zero. This approach assumes, theat only one key/value pair exists in the object.
var [key, value] = Object.entries(object.clauses[0])[0];
// ^^^^^^^^^^^^ target by destructuring an array
// ^^^^^^ source
// ^^^^^^^ property
// ^^^ index/the first one
// ^^^^^^^^^^^^^^ ^ get all key/value pairs of object
// ^^^ take the first pair only
You can use the Array.find() method and verify if the object keys have the value you need.
clauses.find(object => Object.keys(object).includes('2.2.10.60'))
This will return an array of the first object whose keys include '2.2.10.60'
Task: convert an array into an object with one key-value pair, where the first array item is the key, and the last array item is the value.
E.g., [1,2,3] should convert to {1: 3}
I can't get it to work as:
function transformFirstAndLast(array) {
var firstLast = {
array[0]: array[-1]
};
return firstLast
}
But only as:
function transformFirstAndLast(array) {
var firstLast = {};
firstLast[array[0]] = array[array.length - 1];
return firstLast
}
...why doesn't the first work? Why can't you index the array for the key & value?
You could pop the last element and take a computed property for the object. (For the first element, you could take Array#shift, if you like to do it in the same manner.)
function transformFirstAndLast(array) {
return { [array[0]]: array.pop() };
}
console.log(transformFirstAndLast([1, 2, 3]));
ES5 with a temporary variable.
function transformFirstAndLast(array) {
var temp = {};
temp[array[0]] = array.pop();
return temp;
}
console.log(transformFirstAndLast([1, 2, 3]));
Take the first is easy, take the last is the size minus one like this:
function firstAndLast(array) {
var ary = {};
ary[array[0]] = array[array.length - 1];
return ary;
}
console.log(firstAndLast([1,2,3]))
First, you must remember than an array is a type of JavaScript object and, in JavaScript, an object property (a.k.a. "key") can be accessed or assigned in two ways:
via "dot notation"
object.property = value;
via array syntax
object["property"] = value;
Next, remember that, in JavaScript, if you assign a value to a property that doesn't exist (using either syntax from above), the property will be created, like in the following:
console.log(window.someNewProperty); // undefined
window.someNewProperty = 17; // This causes the property to be created
window["someOtherNewProperty"] = "Voilla!"; // So does this, just with array syntax
console.log(window.someNewProperty); // 17
console.log(window["someOtherNewProperty"]); // "Voilla!"
Now, moving on to the specifics of an array, it's critical to understand the difference between an object property/key name (which is always represented as a string) and an array index (which is always a non-negative integer up to the max integer in JavaScript). So, if you have an array and seemingly assign a value to a negative index, you are actually creating a property that is named the negative index and not actually adding to the length of the array or making a new indexed position in the array. We can see that here:
var myArray = ["a", "b", "c"];
myArray[-1] = 15;
console.log(myArray.length); // 3 not 4
console.log(myArray[-1]); // 15
// Now to prove that -1 is a string name for a new property and not an index:
console.log(myArray); // Notice no 15 in the indexed values?
// And, if we enumerate the object (not just the indexes), we'll see that we actually created
// a property with [-1], not a new index.
for(var prop in myArray){
// Note that prop is not the value of the property, it's the property name itself
console.log(typeof prop, prop, myArray[prop]);
}
So, to sum up, Arrays have non-negative integer indexes to store the items that make up the length of the array, but Arrays are also objects and have properties, like all other objects do. Any bracket assignments that use anything other than non-negative integers as the key name will become new properties, not array indices.
Here is the code
var A = [];
A['key1'] = 'apple';
console.log(A.length);
console.log(A['key1']);
A.length is 0 in the log.... But I just don't get it, apparently A['key1'] has a value 'apple'. Why A.length is 0?
Your are define A is array .Array is not key and value pair,Object only have key value pair
Check the console.log A its still empty
var A = [];
A['key1'] = 'apple';//its not added because is a array
console.log(A);
console.log(A.length);
If you need to add key value pair Define A as a Object.and find the length using Object.keys(A) .It will create array of the Object keys
var A = {};
A['key1'] = 'apple';
console.log(A);
console.log(Object.keys(A).length);
console.log(A.key1.length)
Better see the Difference between an array and an object?
You are using javascript associative array which don't have the built-in function like length to get the number of properties in the array. So Instead of using length function you can use the following line to get the number of properties in the array.
Object.keys(A).length
I have an array like below in java-script
Result = [
{"ID":1,"Type":"Pyramid","Phase":"One"},
{"ID":2,"Type":"Pyramid","Phase":"Two"}
]
I tried accessing the individual values and was able to by the below code
alert(Result[0].ID) or alert(Result[0].Phase)
Is there a way to access this by index? like Result[0][1], i tried but getting [object][object]
also i need to access column count
Please help me
You have array of object and by using for loop you can easily access all element value.
try following
function getValue() {
var keys ;
var Result = [{"ID":1,"Type":"Pyramid","Phase":"One"}, {"ID":2,"Type":"Pyramid","Phase":"Two"}]
for(var i=0; i<Result.length;i++){
keys = [];
for(var k in Result[i]){
keys.push(k);
}
for(var k=0;k<keys.length;k++){
console.log(keys[k]+"="+ Result[i][keys[k]]);
}
console.log("key count =" +keys.length);
}
}
CHECK THIS
from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
alert(Result[0][Object.keys(Result[0])[0]]);
Result[0] gets the first row
Object.keys(Result[0]) gets the keys in the first row
Object.keys(Result[0])[0] gets the first column name.
Object.keys(Result[0]).length is the column count in the first row.
Also, objects are not indexed based on a linear integer index as arrays are, so assigning ordered numbers to the unordered list of keys is not right.
A two dimensional array would look like this:
Result = [
[1,"Pyramid","One"],
{2,"Pyramid","Two"}
]
in this case, you could address each field like so: Result[row][col] thus Result[0][2] would yield One.
To access fields in an array of object use the syntax you have provided. Also, why would you want to access the fields in your objects based on id? Or why would you not use an array of arrays?
Your Result is an array of object, then you must first get an object, and then get the property of your object. This is not a multidimensional array.
You array has an object we have to convert that object to array. So converting whole var Result to newResult you can access newResult and it's component through index number
Result = [
{"ID":1,"Type":"Pyramid","Phase":"One"},
{"ID":2,"Type":"Pyramid","Phase":"Two"}
];
var newResult = [];
for (var i = 0; i < Result.length; i++) {
newResult[i] = [];
for (var x in Result[i]) {
if (Result[i].hasOwnProperty(x)) {
newResult[i].push(Result[i][x]);
}
};
};
console.log(newResult);
Use newResult instead of Result
You can get ID by newResult[0][0]
http://jsfiddle.net/LLz1cbok/
I am using jQuery to iterate through a Javascript object and I would like to set the key value of one or more of the objects keys from within the loop.
var children = $(clone).children();
$.each(obj, function(k, v) {
if(v == undefined) {
//Loop through data array and match.
for(var i=0; i<children.length; i++) {
var dataId = children[i].id.split('.');
if(k == dataId[1]) {
obj.k = children[i].value; //This is the value I want to set on the key.
}
}
}
});
The children variable is an array of children (input and select objects) within a div. The loop is passed an object and runs through all the keys in the object. In this case the object is a phone numbers and its keys are similar to number, type, primary etc. but that doesn't matter much. If a key on the object is undefined I want to populate that key with a value from its matching child object.
Everything is working perfectly except I cannot figure out how to set the key with a new value.
use
obj[k] = children[i].value;
note that foo['bar'] is equivalent to foo.bar