4

I have create one object and that object I need to pass in one method where I need to iterate by using each object. Since my Obj having only values so it its not getting passed. Can any one help me into this.

My Code :

var MyObj = {
    country : "Aus",
    Time : "EST",
    Val : "Pecific"
}

Now this MyObj I need to pass in one method:

this.someMethod(id, MyObj);

In someMethod i Have one code like

Ext.Array.forEach(MyObj, function (Value) {})

At this point it is getting failed because MyObj is not an array of object. How to correct it.

David
  • 4,266
  • 8
  • 34
  • 69

4 Answers4

3

It would be very helpful if you'd provide more information.

I am not sure what you want to achieve, but there are several ways to iterate through objects.

If you want to split up your object into multiple single-key objects:

> Object.keys(MyObj).map(key => ({ [key]: MyObj[key] }))
[ { country: 'Aus' }, { Time: 'EST' }, { Val: 'Pecific' } ]

On the other hand, if you have a function that takes an array but you want to pass just this one object:

Ext.Array.forEach([MyObj], Value => ())

(But in this case you are better off just calling the function.)

Alex Pánek
  • 413
  • 2
  • 8
3

var MyObj = {
    country : "Aus",
    Time : "EST",
    Val : "Pecific"
}

//Without ext
function someMethod(id, MyObj)
{
  Object.keys(MyObj).forEach(function (Value) {
console.log(MyObj[Value]);
});
}

someMethod(1, MyObj);

This code (vanilla JS) will get the keys from the Object with Object.keys and allows you to iterate over it. Works for Objects and Arrays.

Mouser
  • 13,132
  • 3
  • 28
  • 54
3

You can achieve that in the following way:

var MyObj = {
    country : "Aus",
    Time : "EST",
    Val : "Pecific"
}

function someFunction(id, obj){
  var objArray = $.map(obj, function(el) { 
    console.log(el);
    return el 
  });
}
someFunction(1, MyObj)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • 1
    why are you introducing a library like jQuery to do something that can be handled by Vanilla JS? – Mouser Mar 14 '17 at 10:58
3

The ExtJs way

ExtJs provides Ext.Object.eachValue which is what you are searching for.
From the ExtJs documentation:

Iterates through an object and invokes the given callback function for each iteration. The iteration can be stopped by returning false in the callback function.

The following code iterrates over each value of MyObj and calls the callback with it.

var MyObj = {
    country : "Aus",
    Time : "EST",
    Val : "Pecific"
}

Ext.Object.eachValue(MyObj, function (Value) {console.log(Value)});
And-y
  • 1,519
  • 2
  • 22
  • 33