0

Suppose I have the following array:

var sample: [{
  pin_code: "110015",
  city: "New Delhi",
  address: "xyz",
}]

I want the output as:

var sample: [{
  address: "xyz",
  city: "New Delhi",
  pin_code: "110015",  
}] // arranging the keys alphabetically
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 1
    Any code which accesses an object shouldn't rely on the order of properties. As such, this seems like an X/Y question - what is the actual goal you're trying to reach given the ordered output? – Rory McCrossan Nov 22 '22 at 14:50
  • I don't think you can change the order of an object keys but what you can do is copy the keys of your object in an array, sort them, and create a new object with the sorted keys. For you **specific** example only: `const sample = [{ pin_code: "110015", city: "New Delhi", address: "xyz", }] let keys = Object.keys(sample[0]) keys.sort((a,b)=> a.localeCompare(b)) const newObject = { keys[0]: sample[0][`$keys[0]}`] keys[1]: sample[0][`$keys[1]}`] keys[2]: sample[0][`$keys[2]}`] }` – Marios Nov 22 '22 at 15:06
  • @Marios it is possible I just made a function that does what he's looking for... – Moussa Bistami Nov 22 '22 at 15:07

1 Answers1

0

I wrote a function that gets the total keys and inserts it in a new object then returns the object if you don't understand anything let me know in the comments I'll explain!

var sample= [{
  pin_code: "110015",
  city: "New Delhi",
  address: "xyz",
},{
  pin_code: "110015",
  city: "New Delhi",
  address: "xyz",
}]
const sort_keys = (obj) =>{
  const new_ordered_sample = []
  const keys= []
  obj.map((o,i) => {
    keys[i] = []; 
    Object.keys(o).map((v, j)=>keys[i].push(v))
    let newObj = {};
    keys[i].sort().map((e)=>{
      newObj[e] = obj[i][e]
    })
    new_ordered_sample.push(newObj)
  })
  return (new_ordered_sample)
}
sample = sort_keys(sample)
console.log(sample)

PS: Tested and working! you can edit the sample and add as many objects as you want!

Moussa Bistami
  • 929
  • 5
  • 15