If there is a JavaScript object:
var objects={...};
Suppose, it has more than 50 properties, without knowing the property names (that's without knowing the 'keys') how to get each property value in a loop?
Depending on which browsers you have to support, this can be done in a number of ways. The overwhelming majority of browsers in the wild support ECMAScript 5 (ES5), but be warned that many of the examples below use Object.keys, which is not available in IE < 9. See the compatibility table.
ECMAScript 3+
If you have to support older versions of IE, then this is the option for you:
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var val = obj[key];
// use val
}
}
The nested if makes sure that you don't enumerate over properties in the prototype chain of the object (which is the behaviour you almost certainly want). You must use
Object.prototype.hasOwnProperty.call(obj, key) // ok
rather than
obj.hasOwnProperty(key) // bad
because ECMAScript 5+ allows you to create prototypeless objects with Object.create(null), and these objects will not have the hasOwnProperty method. Naughty code might also produce objects which override the hasOwnProperty method.
ECMAScript 5+
You can use these methods in any browser that supports ECMAScript 5 and above. These get values from an object and avoid enumerating over the prototype chain. Where obj is your object:
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var val = obj[keys[i]];
// use val
}
If you want something a little more compact or you want to be careful with functions in loops, then Array.prototype.forEach is your friend:
Object.keys(obj).forEach(function (key) {
var val = obj[key];
// use val
});
The next method builds an array containing the values of an object. This is convenient for looping over.
var vals = Object.keys(obj).map(function (key) {
return obj[key];
});
// use vals array
If you want to make those using Object.keys safe against null (as for-in is), then you can do Object.keys(obj || {})....
Object.keys returns enumerable properties. For iterating over simple objects, this is usually sufficient. If you have something with non-enumerable properties that you need to work with, you may use Object.getOwnPropertyNames in place of Object.keys.
ECMAScript 2015+ (A.K.A. ES6)
Arrays are easier to iterate with ECMAScript 2015. You can use this to your advantage when working with values one-by–one in a loop:
for (const key of Object.keys(obj)) {
const val = obj[key];
// use val
}
Using ECMAScript 2015 fat-arrow functions, mapping the object to an array of values becomes a one-liner:
const vals = Object.keys(obj).map(key => obj[key]);
// use vals array
ECMAScript 2015 introduces Symbol, instances of which may be used as property names. To get the symbols of an object to enumerate over, use Object.getOwnPropertySymbols (this function is why Symbol can't be used to make private properties). The new Reflect API from ECMAScript 2015 provides Reflect.ownKeys, which returns a list of property names (including non-enumerable ones) and symbols.
Array comprehensions (do not attempt to use)
Array comprehensions were removed from ECMAScript 6 before publication. Prior to their removal, a solution would have looked like:
const vals = [for (key of Object.keys(obj)) obj[key]];
// use vals array
ECMAScript 2017+
ECMAScript 2016 adds features which do not impact this subject. The ECMAScript 2017 specification adds Object.values and Object.entries. Both return arrays (which will be surprising to some given the analogy with Array.entries). Object.values can be used as is or with a for-of loop.
const values = Object.values(obj);
// use values array or:
for (const val of Object.values(obj)) {
// use val
}
If you want to use both the key and the value, then Object.entries is for you. It produces an array filled with [key, value] pairs. You can use this as is, or (note also the ECMAScript 2015 destructuring assignment) in a for-of loop:
for (const [key, val] of Object.entries(obj)) {
// use key and val
}
Object.values shim
Finally, as noted in the comments and by teh_senaus in another answer, it may be worth using one of these as a shim. Don't worry, the following does not change the prototype, it just adds a method to Object (which is much less dangerous). Using fat-arrow functions, this can be done in one line too:
Object.values = obj => Object.keys(obj).map(key => obj[key]);
which you can now use like
// ['one', 'two', 'three']
var values = Object.values({ a: 'one', b: 'two', c: 'three' });
If you want to avoid shimming when a native Object.values exists, then you can do:
Object.values = Object.values || (obj => Object.keys(obj).map(key => obj[key]));
Finally...
Be aware of the browsers/versions you need to support. The above are correct where the methods or language features are implemented. For example, support for ECMAScript 2015 was switched off by default in V8 until recently, which powered browsers such as Chrome. Features from ECMAScript 2015 should be be avoided until the browsers you intend to support implement the features that you need. If you use babel to compile your code to ECMAScript 5, then you have access to all the features in this answer.
By using a simple for..in loop:
for(var key in objects) {
var value = objects[key];
}
Here's a reusable function for getting the values into an array. It takes prototypes into account too.
Object.values = function (obj) {
var vals = [];
for( var key in obj ) {
if ( obj.hasOwnProperty(key) ) {
vals.push(obj[key]);
}
}
return vals;
}
If you have access to Underscore.js, you can use the _.values function like this:
_.values({one : 1, two : 2, three : 3}); // return [1, 2, 3]
ES5 Object.keys
var a = { a: 1, b: 2, c: 3 };
Object.keys(a).map(function(key){ return a[key] });
// result: [1,2,3]
If you really want an array of Values, I find this cleaner than building an array with a for ... in loop.
ECMA 5.1+
function values(o) { return Object.keys(o).map(function(k){return o[k]}) }
It's worth noting that in most cases you don't really need an array of values, it will be faster to do this:
for(var k in o) something(o[k]);
This iterates over the keys of the Object o. In each iteration k is set to a key of o.
const myObj = { a:1, b:2, c:3 }
Get all values:
the shortest way:
const myValues = Object.values(myObj)
const myValues = Object.keys(myObj).map(key => myObj[key])
You can loop through the keys:
foo = {one:1, two:2, three:3};
for (key in foo){
console.log("foo["+ key +"]="+ foo[key]);
}
will output:
foo[one]=1
foo[two]=2
foo[three]=3
ECMA2017 onwards:
Object.values(obj) will fetch you all the property values as an array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
The question doesn't specify whether wanting inherited and non-enumerable properties also.
There is a question for getting everything, inherited properties and non-enumerable properties also, that Google cannot easily find.
If we are to get all inherited and non-enumerable properties, my solution for that is:
function getAllPropertyNames(obj) {
let result = new Set();
while (obj) {
Object.getOwnPropertyNames(obj).forEach(p => result.add(p));
obj = Object.getPrototypeOf(obj);
}
return [...result];
}
And then iterate over them, just use a for-of loop:
function getAllPropertyNames(obj) {
let result = new Set();
while (obj) {
Object.getOwnPropertyNames(obj).forEach(p => result.add(p));
obj = Object.getPrototypeOf(obj);
}
return [...result];
}
let obj = {
abc: 123,
xyz: 1.234,
foobar: "hello"
};
for (p of getAllPropertyNames(obj)) console.log(p);
For those early adapting people on the CofeeScript era, here's another equivalent for it.
val for key,val of objects
Which may be better than this because the objects can be reduced to be typed again and decreased readability.
objects[key] for key of objects
Apparently - as I recently learned - this is the fastest way to do it:
var objs = {...};
var objKeys = Object.keys(obj);
for (var i = 0, objLen = objKeys.length; i < objLen; i++) {
// do whatever in here
var obj = objs[objKeys[i]];
}
use a polyfill like:
if(!Object.values){Object.values=obj=>Object.keys(obj).map(key=>obj[key])}
then use
Object.values(my_object)
3) profit!
const object1 = {
a: 'somestring',
b: 42
};
for (let [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
// expected output:
// "a: somestring"
// "b: 42"
// order is not guaranteed
I realize I'm a little late but here's a shim for the new firefox 47 Object.values method
Object.prototype.values = Object.prototype.values || function(obj) {
return this.keys(obj).map(function(key){
return obj[key];
});
};
Object.entries do it in better way.
var dataObject = {"a":{"title":"shop"}, "b":{"title":"home"}}
Object.entries(dataObject).map(itemArray => {
console.log("key=", itemArray[0], "value=", itemArray[1])
})
Use: Object.values(), we pass in an object as an argument and receive an array of the values as a return value.
This returns an array of a given object own enumerable property values. You will get the same values as by using the for in loop but without the properties on the Prototype. This example will probably make things clearer:
function person (name) {
this.name = name;
}
person.prototype.age = 5;
let dude = new person('dude');
for(let prop in dude) {
console.log(dude[prop]); // for in still shows age because this is on the prototype
} // we can use hasOwnProperty but this is not very elegant
// ES6 +
console.log(Object.values(dude));
// very concise and we don't show props on prototype
Here's a function similar to PHP's array_values()
function array_values(input) {
var output = [], key = '';
for ( key in input ) { output[output.length] = input[key]; }
return output;
}
Here's how to get the object's values if you're using ES6 or higher:
Array.from(values(obj));
Compatible with ES7 even some browsers do not support it yet
Since , Object.values(<object>) will be built-in in ES7 &
Until waiting all browsers to support it , you could wrap it inside a function :
Object.vals=(o)=>(Object.values)?Object.values(o):Object.keys(o).map((k)=>o[k])
Then :
Object.vals({lastname:'T',firstname:'A'})
// ['T','A']
Once browsers become compatible with ES7, you will not have to change anything in your code.
we can fetch data using three methods below
Use map function
data.map( item => { console.log(item) }
Use for loop
for( let i = 0; i < data.length; i++){
console.log(item);
}
Use for in loop
for(key in data) {
if(data.hasOwnProperty(key)) {
const value = data[key];
console.log(value);
}
}
I think the easiest option is like this:
Object.keys(data).forEach(function (key, index) {
var value = data[key];
console.log(key, index, value);
});
For example, a runnable code is added here:
const user = {
name: 'Alex',
age: 30,
};
Object.keys(user).forEach(function (key, index) {
var value = user[key];
console.log(key, index, value);
});
var objects={...}; this.getAllvalues = function () {
var vls = [];
for (var key in objects) {
vls.push(objects[key]);
}
return vls;
}
in ECMAScript5 use
keys = Object.keys(object);
Otherwise if you're browser does not support it, use the well-known for..in loop
for (key in object) {
// your code here
}
Now I use Dojo Toolkit because older browsers do not support Object.values.
require(['dojox/lang/functional/object'], function(Object) {
var obj = { key1: '1', key2: '2', key3: '3' };
var values = Object.values(obj);
console.log(values);
});
Output :
['1', '2', '3']
use
console.log(variable)
and if you using google chrome open Console by using Ctrl+Shift+j
Goto >> Console
I am still somewhat new to JavaScript, Node, etc. and come from a Groovy background (which has extremely similar syntax to JavaScript). In Groovy, I can easily do something like this:
def myMap1 = {};
def myMap2 = {};
myMap1["key1"] = "value1";
myMap1["key2"] = "value2";
myMap1["key3"] = "value3";
myMap1.each() { key, value =>
myMap2[key] = value;
}
This would iterate through the existing map (myMap1) and copy the values for each key to the new map (myMap2), with the same key names. Easy as pie. However, JS has a concept of the prototype, which has been driving me crazy because you have to use hasOwnProperty, the index of the item sort of thing, etc and it results in a lot of code for something that's supposed to be really simple.
Looking at the MDN docs for Object(), it looks like JS has implemented something that allows a developer to access key/value pairs without having to deal with prototyping and all of that stuff, and you can just access the data in the object, and not properties of the object. I now have this:
var existingData = {"foo":"thing","bar":"otherThing","baz":"whatever"};
var update = {"foo":"newStuff","bar":"thisChanged","baz":"arghh"};
for (const [ key, value ] of Object.entries(update)) {
console.log("Old value is " + existingData[key]);
existingData[key] = value;
console.log("Setting " + existingData[key] + " to " + value);
}
I would think this would work, but I get this in the console instead:
Old value is undefined
Setting thing to thing
Old value is undefined
Setting otherThing to otherThing
Old value is undefined
Setting whatever to whatever
It looks like existingData[key] does not reference the key in the key/value pair, but instead the value or something? How do I tell it, "for this key name in this second object, set this value?" I've been searching forever on Google and everything is either doing it the old way (with indexes) or is overly complicated for no particular reason. Any help would be greatly appreciated.
for (let key in map1) {
map2[key] = map1[key];
}
BTW why you dont use Object.assign(); ? (notice: it returns a new object)
let update = { "key1": "value1", "key2": "value2" };
let map2 = Object.assign({}, map1, update);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Simply use Object.assign(map2, map1) to update map2 (copy key/value of map1 to map2)
Or you can use,
map2 = {...map2, ...map1} to build a new object and replace the map2 completely
To have a deep copy, instead of only first level you can use JSON.parse(JSON.stringify(map2)) instead of map2. If you think, its a large object and that impact performance, go for a nested implementation of copy recursively! ;-)
You could just do this - looping through an array of the keys:
let myMap1 = {};
let myMap2 = {};
myMap1["key1"] = "value1";
myMap1["key2"] = "value2";
myMap1["key3"] = "value3";
// create an array of the keys in the object myMap1
let myMap1_keys = Object.keys(myMap1);
// loop through the array of object keys
for (let i = 0; i < myMap1_keys.length; i++) {
myMap2[myMap1_keys[i]] = myMap1[myMap1_keys[i]];
}
I would advise not using a for..in loop i.e. as used in one of the other answers as these are slower than a native for loop (as used above). You can see some details regarding performance here: Comparing JavaScript loops performance (for, do while, for in)
If you are just interested in literally duplicating the object you can do that like so:
let myMap2 = JSON.parse(JSON.stringify(myMap1));
Anouther answer suggested using Object.assign() and anouther suggested using ES6 spread operators but these will 'shallow' copy the object which means the objects are using references to the original object and will only copy the top level of the object - the method above deep copies the object which I usually find is what is required for most use cases and will copy every level of the object.
You can iterate over keys. check is this helpful to you
var m1 = {};
let m2 = {};
m1["key1"] = "abc";
m1["key2"] = "def";
m1["key3"] = "ghi";
var m1_change_key = Object.keys(m1);
for (var i = 0; i < m1_change_key.length; i++) {
m2[m1_change_key[i]] = m1[m1_change_key[i]];
alert(m2[m1_change_key[i]])
}
I have an object of values and I am trying to populate two arrays with the keys and values from the object.
My Object:
obj = {19455746: 7476, 22489710: 473}
Loop attempting to append data:
var sensorNameArray = [];
var sensorDataArray = [];
for(var i in obj) {
sensorNameArray.push[i];
sensorDataArray.push[obj[i]];
}
At the moment the two arrays are printing out as empty. My expected outout would be something like:
sensorNameArray = [19455746, 22489710];
sensorDataArray = [7476, 473];
push is a function, not an array, it uses parenthesis not brackets :
for(var i in obj) {
sensorNameArray.push(i);
sensorDataArray.push(obj[i]);
}
The syntax push[] doesn't invoke the function, it tries to access a property of the function object. It doesn't throw an error because in Javascript, functions ARE objects and this syntax is technically valid.
So, just fix the syntax to push() in order to actually invoke the function.
You are using square braces []
but array.push() is a function so use circle braces instead
Try the following code
obj = {19455746: 7476, 22489710: 473};
var sensorNameArray = [];
var sensorDataArray = [];
for(var i in obj) {
sensorNameArray.push(i);
sensorDataArray.push(obj[i]);
}
This is working and tested.
A different syntax (more elegant IMO) :
var sensorNameArray = Object.keys(obj)
var sensorDataArray = Object.values(obj)
or :
var sensorDataArray = sensorNameArray.map( key => obj[key] )
Best way to deal with JSON is use lodash or underscore.
_.key() and _.value are functions for your requirement.
Eg.:
obj = {19455746: 7476, 22489710: 473};
sensorNameArray = _.keys(obj);
sensorDataArray = _.values(obj);
If you want to proceed in your way, then you can use parenthesis as push inbuilt function of Javascript for inserting element into array.
Correct is:
for(var i in obj) {
sensorNameArray.push(i);
sensorDataArray.push(obj[i]);
}
I have a object map in JavaScript and I have to read it.
The object map is:
network[0]
Object {dpi: "user2"}
I have used this to read the key:
demp=Object.keys(network[0]);
sourceNodeFirewall = demp[0];
But I'm not able to read the value ("user2").
I know that I can do this:
network[0].dpi
in order to have user2, but during a for cycle I have no idea to do it, in addition that the key can change in any value.
I cannot put the real code because it is very complicate but an simple example is:
The object is set in this way:
var network = {};
network[$("#0B").val()] = $("#0BB").val();
Where I have a key and I value.
After that I wish to get the value and the key.
demp stores all key of the object, You need to access the property from the network[0] object.
var network = [{dpi: "user2"}];
demp = Object.keys(network[0]);
console.log(network[0][demp[0]]);
You can access an object's properties by indexing into it with square brackets:
var network = [{dpi: "user2"}];
console.log(network[0]);
var demp = Object.keys(network[0]);
var sourceNodeFirewall = demp[0];
var propValue = network[0][demp[0]];
console.log(propValue);
In a for loop you need to iterate over each key in the map, and to access the value just lookup the map with that key as the index.
var network = {
dpi: "user2"
}
for (var key in network) {
console.log(network[key]);
}
As you referred to a for loop, here what I think you are looking for:
const obj = {
dpi: "user2"
};
for(key in obj){
console.log(obj[key]);
}
Or maybe using a forEach:
const obj = {
dpi: "user2"
};
Object.keys(obj).forEach(
key => console.log(obj[key])
)
This should be pretty easy but I'm a little confused here. I want to fill this object:
var obj = { 2:some1, 14:some2, three:some3, XX:some4, five:some5 };
but in the start I have this:
var obj = {};
I´m making a for but I don't know how to add, I was using push(), but is not working. Any help?
You can't .push() into a javascript OBJECT, since it uses custom keys instead of index. The way of doing this is pretty much like this:
var obj = {};
for (var k = 0; k<10; k++) {
obj['customkey'+k] = 'some'+k;
}
This would return:
obj {
customkey0 : 'some0',
customkey1 : 'some1',
customkey2 : 'some2',
...
}
Keep in mind, an array: ['some1','some2'] is basicly like and object:
{
0 : 'some1',
1 : 'some2'
}
Where an object replaces the "index" (0,1,etc) by a STRING key.
Hope this helps.
push() is for use in arrays, but you're creating a object.
You can add properties to an object in a few different ways:
obj.one = some1;
or
obj['one'] = some1;
I would write a simple function like this:
function pushVal(obj, value) {
var index = Object.size(obj);
//index is modified to be a string.
obj[index] = value;
}
Then in your code, when you want to add values to an object you can simply call:
for(var i=0; i<someArray.length; i++) {
pushVal(obj, someArray[i]);
}
For info on the size function I used, see here. Note, it is possible to use the index from the for loop, however, if you wanted to add multiple arrays to this one object, my method prevents conflicting indices.
EDIT
Seeing that you changed your keys in your questions example, in order to create the object, you can use the following:
function pushVal(obj, value, key) {
//index is modified to be a string.
obj[key] = value;
}
or
obj[key] = value;
I'm not sure how you determine your key value, so without that information, I can't write a solution to recreate the object, (as is, they appear random).