for (var k in target){
if (target.hasOwnProperty(k)) {
alert("Key is " + k + ", value is " + target[k]);
}
}
hasOwnProperty is used to check if your target really has that property, rather than having inherited it from its prototype. A bit simpler would be:
for (var k in target){
if (typeof target[k] !== 'function') {
alert("Key is " + k + ", value is" + target[k]);
}
}
It just checks that k is not a method (as if target is array you'll get a lot of methods alerted, e.g. indexOf, push, pop,etc.)
for (var k in target){
if (target.hasOwnProperty(k)) {
alert("Key is " + k + ", value is " + target[k]);
}
}
hasOwnProperty is used to check if your target really has that property, rather than having inherited it from its prototype. A bit simpler would be:
for (var k in target){
if (typeof target[k] !== 'function') {
alert("Key is " + k + ", value is" + target[k]);
}
}
It just checks that k is not a method (as if target is array you'll get a lot of methods alerted, e.g. indexOf, push, pop,etc.)
If you can use ES6 natively or with Babel (js compiler) then you could do the following:
const test = {a: 1, b: 2, c: 3};
for (const [key, value] of Object.entries(test)) {
console.log(key, value);
}
Which will print out this output:
a 1
b 2
c 3
The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
- Object.entries documentation
- for...of documentation
- Destructuring assignment documentation
- Enumerability and ownership of properties documentation
How would I access the first key-value pair of the "files" object using a forEach loop?
Is Object.keys(obj).forEach really any better than for-in loop?
How do i remove elements from a list while in a foreach loop?
Loop through an object inside of the render method?
Map over the keys of the object using Object.keys():
{Object.keys(yourObject).map(function(key) {
return <div>Key: {key}, Value: {yourObject[key]}</div>;
})} More on reddit.com Videos
Here's how the JSON looks
"files": {
"file1": {
"filename": "file1",
"timestamp": 1073692
}
}It's basically a value that is contained by every object in the array and I need to access the filename key that's inside every object.
Hope this makes sense
edit: the object key matches the file name every time