简体   繁体   中英

How to iterate an object into an array of Object

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.

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)});

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.)

 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.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM