$VAR1 = {
'time_stamp' => '06/20/13 09:53',
'data' => {
'TOS1' => {
'69' => {
'65' => {
'LINK_STATUS' => 1,
'KPIS' => {
Aailability' => {
'status' => 'G',
'val' => '100'
},
'Completion Time' => {
'status' => 'G',
'val' => '1'
}
}
}
}
}
}
};
I want to convert this hash in to an array. i got this in json and store it in one variable in javascript. i want display this all values in tabular format
plz suggest me
So what you have there is a deeply-nested object graph. To make an array out of it, you'd probably use for-in to loop through the properties of the object at each level and use the values to build up an array. It's not remotely clear from the question what you might want that array to look like, so I can't really help further.
Here's what a for-in loop looks like:
var key;
for (key in obj) {
// Here, `key` will have each property name; to get
// that property's value, use obj[key]
}
So for example:
var obj = {
a: 1,
b: 2
};
var key;
for (key in obj) {
console.log(key + "=" + obj[key]);
}
...will output
a=1
b=2
(the order isn't guaranteed).
I don't see any reason to convert that to an array. In Javascript arrays can only have numerical keys.
You can iterate over the object properties with a for in:
for (var property in $VAR1) {
if ($VAR1.hasOwnProperty(property)) {
console.log(property); // time_stamp
console.log($VAR1[property]); // 06/20/13 09:53
}
}
Given that you have nested objects, you'd need nested loops to iterate over the nested objects.
Related
This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 12 months ago.
I have a dictionary that has the format of
dictionary = {0: {object}, 1:{object}, 2:{object}}
How can I iterate through this dictionary by doing something like
for ((key, value) in dictionary) {
//Do stuff where key would be 0 and value would be the object
}
tl;dr
In ECMAScript 2017, just call Object.entries(yourObj).
In ECMAScript 2015, it is possible with Maps.
In ECMAScript 5, it is not possible.
ECMAScript 2017
ECMAScript 2017 introduced a new Object.entries function. You can use this to iterate the object as you wanted.
'use strict';
const object = {'a': 1, 'b': 2, 'c' : 3};
for (const [key, value] of Object.entries(object)) {
console.log(key, value);
}
Output
a 1
b 2
c 3
ECMAScript 2015
In ECMAScript 2015, there is not Object.entries but you can use Map objects instead and iterate over them with Map.prototype.entries. Quoting the example from that page,
var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
var mapIter = myMap.entries();
console.log(mapIter.next().value); // ["0", "foo"]
console.log(mapIter.next().value); // [1, "bar"]
console.log(mapIter.next().value); // [Object, "baz"]
Or iterate with for..of, like this
'use strict';
var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
for (const entry of myMap.entries()) {
console.log(entry);
}
Output
[ '0', 'foo' ]
[ 1, 'bar' ]
[ {}, 'baz' ]
Or
for (const [key, value] of myMap.entries()) {
console.log(key, value);
}
Output
0 foo
1 bar
{} baz
ECMAScript 5:
No, it's not possible with objects.
You should either iterate with for..in, or Object.keys, like this
for (var key in dictionary) {
// check if the property/key is defined in the object itself, not in parent
if (dictionary.hasOwnProperty(key)) {
console.log(key, dictionary[key]);
}
}
Note: The if condition above is necessary only if you want to iterate over the properties which are the dictionary object's very own. Because for..in will iterate through all the inherited enumerable properties.
Or
Object.keys(dictionary).forEach(function(key) {
console.log(key, dictionary[key]);
});
Try this:
dict = {0:{1:'a'}, 1:{2:'b'}, 2:{3:'c'}}
for (var key in dict){
console.log( key, dict[key] );
}
0 Object { 1="a"}
1 Object { 2="b"}
2 Object { 3="c"}
WELCOME TO 2020 *Drools in ES6*
Theres some pretty old answers in here - take advantage of destructuring. In my opinion this is without a doubt the nicest (very readable) way to iterate an object.
const myObject = {
nick: 'cage',
phil: 'murray',
};
Object.entries(myObject).forEach(([k,v]) => {
console.log("The key: ", k)
console.log("The value: ", v)
})
Edit:
As mentioned by Lazerbeak, map allows you to cycle an object and use the key and value to make an array.
const myObject = {
nick: 'cage',
phil: 'murray',
};
const myArray = Object.entries(myObject).map(([k, v]) => {
return `The key '${k}' has a value of '${v}'`;
});
console.log(myArray);
Edit 2:
To explain what is happening in the line of code:
Object.entries(myObject).forEach(([k,v]) => {}
Object.entries() converts our object to an array of arrays:
[["nick", "cage"], ["phil", "murray"]]
Then we use forEach on the outer array:
1st loop: ["nick", "cage"]
2nd loop: ["phil", "murray"]
Then we "destructure" the value (which we know will always be an array) with ([k,v]) so k becomes the first name and v becomes the last name.
The Object.entries() method has been specified in ES2017 (and is supported in all modern browsers):
for (const [ key, value ] of Object.entries(dictionary)) {
// do something with `key` and `value`
}
Explanation:
Object.entries() takes an object like { a: 1, b: 2, c: 3 } and turns it into an array of key-value pairs: [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ].
With for ... of we can loop over the entries of the so created array.
Since we are guaranteed that each of the so iterated array items is itself a two-entry array, we can use destructuring to directly assign variables key and value to its first and second item.
Try this:
var value;
for (var key in dictionary) {
value = dictionary[key];
// your code here...
}
You can do something like this :
dictionary = {'ab': {object}, 'cd':{object}, 'ef':{object}}
var keys = Object.keys(dictionary);
for(var i = 0; i < keys.length;i++){
//keys[i] for key
//dictionary[keys[i]] for the value
}
I think the fast and easy way is
Object.entries(event).forEach(k => {
console.log("properties ... ", k[0], k[1]); });
just check the documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
using swagger-ui.js
you can do this -
_.forEach({ 'a': 1, 'b': 2 }, function(n, key) {
console.log(n, key);
});
You can use below script.
var obj={1:"a",2:"b",c:"3"};
for (var x=Object.keys(obj),i=0;i<x.length,key=x[i],value=obj[key];i++){
console.log(key,value);
}
outputs
1 a
2 b
c 3
As an improvement to the accepted answer, in order to reduce nesting, you could do this instead, provided that the key is not inherited:
for (var key in dictionary) {
if (!dictionary.hasOwnProperty(key)) {
continue;
}
console.log(key, dictionary[key]);
}
Edit: info about Object.hasOwnProperty here
You can use JavaScript forEach Loop:
myMap.forEach((value, key) => {
console.log('value: ', value);
console.log('key: ', key);
});
Here I want to read key name of obj.
Like "CIRTGroupBox1", "CIRTGroupBox2"
Try this :
var arr = [{
'CIRTGroupBox1': ''
}, {
'CIRTGroupBox2': ''
}, {
'CIRTGroupBox3': ''
}];
// Using array.map() method
var usingMapKeys = arr.map((obj) => Object.keys(obj)[0]);
// Using Object.entries() method
var usingEnteriesKeys = arr.map((obj) => Object.entries(obj)[0][0]);
console.log(usingMapKeys);
console.log(usingEnteriesKeys);
is it?
var x = {
"ob1": "value",
"ob2": {
"ob21": "value"
}
};
var keys = Object.keys(x);
console.log(keys);
You can do that using Object.keys method in JS like below
var keys = Object.keys(groupBoxesTemp);
This will return string array and each item in it is the key of this object.
If you want to read values pertaining those 2 keys, you can do like below using the for-in loop:
for(item in groupBoxesTemp){
console.log('key is: ', item);
console.log('value is: ', groupBoxesTemp[item]);
}
Based on your screenshot, temp is an array of objects which has 3 objects in it. You can do that too like below:
temp.forEach(function(item, index){
//key for all objects in the array will be logged.
console.log( Object.keys(item) );
});
I have an object named options. I need to do something like below where if a property is already set, update it otherwise don't do anything:
if (options.A)
options.A = formatMessage(options.A);
if (options.B)
options.B = formatMessage(options.B);
if (options.C)
options.C = formatMessage(options.C);
if (options.D)
options.D = formatMessage(options.D);
Is there a better way to check if a particular property of an object is set and then update in pure JavaScript?
Iterate over an array of key names - if the retrieved value at each key is truthy, call the function and reassign it:
['A', 'B', 'C', 'D'].forEach((key) => {
if (options[key]) {
options[key] = formatMessage(options[key]);
}
});
If these are the only keys that might exist, you might consider using .reduce into a new object instead, thereby avoiding unnecessary mutation:
const formattedOptions = Object.entries(options).reduce((a, [key, val]) => {
a[key] = formatMessage(val);
return a;
}, {});
You can consider this option
const obj = {
'A':'test','B':'test1','C':'test2','D':'test3'
};
Object.keys(obj).map(key=> {
obj[key]=formatMessage(obj[key]);
});
function formatMessage(msg){
return msg + 'translated';
}
console.log(obj);
Here is my example. I have an object in Javascript that is dynamically changed.
And I want in this case the value of the property "inside" and I know that the value is in the place a[something][anotherthing][inside]. Because I saved the position in an array ["a","somethig", "anotherthing"]. my question is How do I move to that position using the keys that are in the array?. Already tried to concat the elements and the final result is something like this myObject[a][somthing][anotherthing] but the problem is that it returns 'undefined' because it's a string. Is there any chance to convert it to object or some way to get that position in the object?
var myarray = ['a', 'something', 'anotherthing'];
myObject = {
a: {
something: {
anotherthing: {
inside: 10
}
}
},
b: {
insideb: {}
}
}
Use reduce to reduce the array to a single value. You will pass in myObject as the starting point (second parameter), then use this basic callback (first parameter):
(obj, itm) => obj[itm]
When you put it all together, it will look like this:
var myarray = ['a', 'something', 'anotherthing'];
myObject = {
a: {
something: {
anotherthing: {
inside: 10
}
}
},
b: {
insideb: {
}
}
}
let result = myarray.reduce((obj, itm) => obj[itm], myObject)
console.log(result)
console.log(result.inside)
If you know the exact location of the value: myObject['a']['somthing']['anotherthing'] will give you the value.
If you need to step through the object dynamically, you can use: Object.keys(myObject).forEach(key => myObject[key]); to get the top level keys.
Say you have a javascript object like this:
var data = { foo: 'bar', baz: 'quux' };
You can access the properties by the property name:
var foo = data.foo;
var baz = data["baz"];
But is it possible to get these values if you don't know the name of the properties? Does the unordered nature of these properties make it impossible to tell them apart?
In my case I'm thinking specifically of a situation where a function needs to accept a series of name-value pairs, but the names of the properties may change.
My thoughts on how to do this so far is to pass the names of the properties to the function along with the data, but this feels like a hack. I would prefer to do this with introspection if possible.
You can loop through keys like this:
for (var key in data) {
console.log(key);
}
This logs "Name" and "Value".
If you have a more complex object type (not just a plain hash-like object, as in the original question), you'll want to only loop through keys that belong to the object itself, as opposed to keys on the object's prototype:
for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(key);
}
}
As you noted, keys are not guaranteed to be in any particular order. Note how this differs from the following:
for each (var value in data) {
console.log(value);
}
This example loops through values, so it would log Property Name and 0. N.B.: The for each syntax is mostly only supported in Firefox, but not in other browsers.
If your target browsers support ES5, or your site includes es5-shim.js (recommended), you can also use Object.keys:
var data = { Name: 'Property Name', Value: '0' };
console.log(Object.keys(data)); // => ["Name", "Value"]
and loop with Array.prototype.forEach:
Object.keys(data).forEach(function (key) {
console.log(data[key]);
});
// => Logs "Property Name", 0
Old versions of JavaScript (< ES5) require using a for..in loop:
for (var key in data) {
if (data.hasOwnProperty(key)) {
// do something with key
}
}
ES5 introduces Object.keys and Array#forEach which makes this a little easier:
var data = { foo: 'bar', baz: 'quux' };
Object.keys(data); // ['foo', 'baz']
Object.keys(data).map(function(key){ return data[key] }) // ['bar', 'quux']
Object.keys(data).forEach(function (key) {
// do something with data[key]
});
ES2017 introduces Object.values and Object.entries.
Object.values(data) // ['bar', 'quux']
Object.entries(data) // [['foo', 'bar'], ['baz', 'quux']]
for(var property in data) {
alert(property);
}
You often will want to examine the particular properties of an instance of an object,
without all of it's shared prototype methods and properties:
Obj.prototype.toString= function(){
var A= [];
for(var p in this){
if(this.hasOwnProperty(p)){
A[A.length]= p+'='+this[p];
}
}
return A.join(', ');
}
function getDetailedObject(inputObject) {
var detailedObject = {}, properties;
do {
properties = Object.getOwnPropertyNames( inputObject );
for (var o in properties) {
detailedObject[properties[o]] = inputObject[properties[o]];
}
} while ( inputObject = Object.getPrototypeOf( inputObject ) );
return detailedObject;
}
This will get all properties and their values (inherited or own, enumerable or not) in a new object. original object is untouched. Now new object can be traversed using
var obj = { 'b': '4' }; //example object
var detailedObject = getDetailedObject(obj);
for(var o in detailedObject) {
console.log('key: ' + o + ' value: ' + detailedObject[o]);
}
var obj = {
a: [1, 3, 4],
b: 2,
c: ['hi', 'there']
}
for(let r in obj){ //for in loop iterates all properties in an object
console.log(r) ; //print all properties in sequence
console.log(obj[r]);//print all properties values
}
You can use Object.keys(), "which returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop."
You can use any object in place of stats:
var stats = {
a: 3,
b: 6,
d: 7,
erijgolekngo: 35
}
/* this is the answer here */
for (var key in Object.keys(stats)) {
var t = Object.keys(stats)[key];
console.log(t + " value =: " + stats[t]);
}
var attr, object_information='';
for(attr in object){
//Get names and values of propertys with style (name : value)
object_information += attr + ' : ' + object[attr] + '\n';
}
alert(object_information); //Show all Object