showing results for - "hange the order of properties in object javascript"
Irene
01 Oct 2017
1// Method 1: Returnes new Object
2function preferredOrder(obj, order) {
3  // returns new object with modified keys
4     const newObj: any = {};
5        for (let key of order) {
6            newObj[key] = obj[key];
7        }
8       return newObj;
9}
10
11// Method 2: Modifies that Object
12 preferredOrder(obj: any, keyOrder: any[]) {
13        // modifies old object with new order
14        keyOrder.forEach((k) => {
15            const v = obj[k]
16            delete obj[k]
17            obj[k] = v
18        })
19    }
20
21
22// preferredOrder({a:'a',b:'b',c:'c'},[b,a,c])
23// output= >  {b:'b',a:'a',c:'c'}
24
25