This question already has answers here:
How to iterate over a JavaScript object?
(19 answers)
Closed 8 years ago.
I am curious but Google is not helping on this one...
We are looking for a tidy way of using an object key (it is an object containing functions) while also having clean access to the key names.
var obj={'key1':'val1','key2':'val2','key3':'val3'};
To get the desired key names in a loop we do: EDIT: this is wrong!
for(var i=0;i<obj.length;i++){
console.log(Object.keys(obj)[i]);
}
but would it be possible in this kind of loop?
for(var k in obj){
//?
}
I have seen combination loops before using &&. Is JavaScript able to do an elegant combination of both?
The closest I have got without disrupting the standard loop is:
var i=0;
for(var k in obj){
console.log(Object.keys(obj)[i]);
i++;
}
but it is hardly elegant, not very innovative, it is more of a work around because 'i' is declared outside of the loop. Everything else we have tried errors.
If I understand your question, it's the simplest ever thing.
for(var k in obj){
console.log(k);
}
Alternatively:
Object.keys(obj).forEach(function(key) { console.log(key); });
If you need the keys:
for(var k in obj) {
console.log(k)
}
If you need the values:
for(var k in obj) {
console.log(obj[k])
}
Are you trying to print out the keys and values?
for(var k in obj){
console.log(k,obj[k]);
}
Related
This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 1 year ago.
I know this question has been asked before but all of the answers assume the array is a 2D array and only go one level deep.
I have a 4D array and have tried some of the solutions here and did not get the result. Here's my array:
I tried this answer from this question but this only goes one level deep. How do I make it work with a 4D array?
var newArray = [];
for (var i = 0; i < currentArray.length; i++)
newArray[i] = currentArray[i].slice();
You could use a simple recursive function that replaces arrays with copies after recursively handling its values:
function deepCopy(value) {
if (Array.isArray(value)) {
return value.map(deepCopy);
}
return value;
}
const data = [[[0]]];
const copy = deepCopy(data);
data[0][0][0] = 123;
console.log(data);
console.log(copy);
Actually looking at the bottom answers of that question, there are already (more complicated) deep copy functions present, such as this one. You can still use mine if you want a very simply only-deep-copies-arrays version of course.
This question already has answers here:
JavaScript Possible Iteration Over Unexpected
(5 answers)
Why is using "for...in" for array iteration a bad idea?
(28 answers)
Closed 5 years ago.
I use phpstorm and over the past half a year or so it started warning me about code like this:
for( let key in attachmentPaths ){
requestObject.formData.attachments.push( fs.createReadStream(attachmentPaths[key]) )
}
Warning on [key]
Possible iteration over unexpected (custom/inherited) members,
probably missing hasOwnProperty check
I understand the warning message, but i don't understand how a for() like this is bad?
Surely additional checks to ensure the key exists with the object is silly as we are looping over the objects found keys..?
Surely additional checks to ensure the key exists with the object
That isn't what the error message says.
The important part is "unexpected (custom/inherited) members".
You could find yourself dealing with extra properties that you weren't expecting which are inherited on the prototype chain.
Consider:
Object.prototype.surprise = "surprise!";
var foo = {
a: 1,
b: 2
};
for (var bar in foo) {
console.log(bar, foo[bar]);
}
You have to check if the object has key if you want to use for in loop.
In javascript, everything is an object. You can assign functions to variables as well. With for ... in loop you are iterating all keys the object has. So if the object has a function that is assigned to a key in the object, you might try to iterate that as well (like the built in functions in strings/arrays etc.)
for( let key in attachmentPaths ){
if(attachmentPaths.hasOwnProperty(key){
requestObject.formData.attachments.push( fs.createReadStream(attachmentPaths[key]) )
}
}
This question already has answers here:
Do modern JavaScript JITers need array-length caching in loops?
(3 answers)
Closed 6 years ago.
This MDN page claims:
...you can iterate over an array using the following:
for (var i = 0; i < a.length; i++) {
// Do something with a[i]
}
This is slightly inefficient as you are looking up the length property
once every loop. An improvement is this:
for (var i = 0, len = a.length; i < len; i++) {
// Do something with a[i]
}
A nicer-looking but limited idiom is:
for (var i = 0, item; item = a[i++];) {
// Do something with item
}
Are these really commonly accepted ways of iteration? Wouldn't modern JavaScript engines simply optimize the first one?
The MDN page is incorrect. Modern engines will optimize the handling of length. In fact, some engines will actually run the first fragment faster.
This question already has answers here:
IE8 for...in enumerator
(3 answers)
How do I check if an object has a specific property in JavaScript?
(31 answers)
Closed 8 years ago.
var arr=["test"]; for(var e in arr) console.log(e);
in IE11's console it outputs:
0 contains remove clear add addAll(all properties)
and in chrome's console only outputs 0, which is expected.
how to fix it in IE? I know I can use for(var i=0;i<arr.length;i++) to solve it.
but I just wonder why IE outputs all the properties.
using IE11 and looks ok to me
if you want more control use Array.prototype.forEach method.It accepts a callback which have three parameters.They are element,their index and the array itself.Try
var arr=["test",'ball'];arr.forEach(function(element,index){
console.log(index);
});
Use the hasOwnProperty method.
Example:
var arr = ["test"];
for (var e in arr) {
if (arr.hasOwnProperty(e)) {
console.log(e);
}
}
Good explanation on why this is necessary: https://stackoverflow.com/a/12017703/1387396
Details on the hasOwnProperty method and its use in for .. in loops: Object.prototype.hasOwnProperty() - JavaScript | MDN
This question already has answers here:
how would I go about accessing a deep value using a single variable in bracket notation?
(3 answers)
Closed 8 years ago.
I want to do this:
market['global']['name']
Like this:
market['global.name'] //undefined
Why? Because it would allow to loop through an array with different 'routes' instead of having to create a ton of exceptions
you coud use something like this for a getter
function get_prop(obj,chain){
chain=chain.split('.');
var nobj={};
for(var i in obj){
if (obj.hasOwnProperty(i)) {
nobj[i]=obj[i];
}
}
for(var i=0; i<chain.length; i++){
if (nobj.hasOwnProperty(chain[i]) {
nobj=nobj[chain[i]];
} else {
return null;
}
}
return nobj;
}
ill post a setter later. but should be something along this lines