Answers for "javascriot object sort properties"

15

sort by object property javascript

let list = [
  {
      name: "world"
  },
  {
      name: "hello",
  },
];

// This doesn't account for if names are the same between objects
let x = list.sort((a, b) => (a.name > b.name ? 1 : -1));

console.log(x);

/*
[
  {
      name: "hello",
  },
  {
      name: "world"
  },
];
*/
Posted by: Guest on August-23-2020
0

hange the order of properties in object javascript

// Method 1: Returnes new Object
function preferredOrder(obj, order) {
  // returns new object with modified keys
     const newObj: any = {};
        for (let key of order) {
            newObj[key] = obj[key];
        }
       return newObj;
}

// Method 2: Modifies that Object
 preferredOrder(obj: any, keyOrder: any[]) {
        // modifies old object with new order
        keyOrder.forEach((k) => {
            const v = obj[k]
            delete obj[k]
            obj[k] = v
        })
    }


// preferredOrder({a:'a',b:'b',c:'c'},[b,a,c])
// output= >  {b:'b',a:'a',c:'c'}
Posted by: Guest on March-26-2021

Code answers related to "javascriot object sort properties"

Code answers related to "Javascript"

Browse Popular Code Answers by Language