0

I have parent object in which data appears as following: name is first, gender is second and address is third

[{name: "alpesh solanki", gender: "male", address: "makarpura GIDC, GIDC Makarpura"},
{name: "alpes", gender: "female", address: "222makarpura GIDC, GIDC Makarpura"}]

I want to push another object in the above array but incoming data is in juggled way, for example

{address: "makarpura GIDC, GIDC Makarpura", gender: "male", name: "alpesh solanki"}

In the sense, address is first, gender is second and name is third

But I want to arrange it according to parent object.

karan patel
  • 61
  • 1
  • 7
  • 1
    Possible duplicate of [Changing the order of the Object keys....](https://stackoverflow.com/questions/6959817/changing-the-order-of-the-object-keys) – MauriceNino Oct 02 '19 at 08:26
  • 1
    You would have to create a new object with your order. But order of properties can never be assured, so don't rely on it. – MauriceNino Oct 02 '19 at 08:27
  • Most browsers keep the order of definition, but this is not required. But it should not matter. If you have to rely on the order of keys in the object, the structure is usually suboptimal. Why do you need the keys to be in order? – Shilly Oct 02 '19 at 08:30

2 Answers2

0

You can't sort properties in an Object.

But if you want to sort properties in every objects of the array you can create a new newData array with the method Array.prototype.map() and Destructuring assignment with the desired properties order data.map(({address, gender, name}) => ({address, gender, name}))

Code:

const data = [{name: "alpesh solanki", gender: "male", address: "makarpura GIDC, GIDC Makarpura"}, {name: "alpes", gender: "female", address: "222makarpura GIDC, GIDC Makarpura"}];
const newData = data.map(({address, gender, name}) => ({address, gender, name}));

console.log(newData);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
0

The sortes approach is to take an object with the wanted keys in order as template and map all object by assigning the properties to a new object with an empty object, the template and the actual object.

The result is an array with object's properties in wanted order.

var data = [{ name: "alpesh solanki", gender: "male", address: "makarpura GIDC, GIDC Makarpura" }, { name: "alpes", gender: "female", address: "222makarpura GIDC, GIDC Makarpura" }],
    template = { address: null, gender: null, name: null },
    result = data.map(o => Object.assign({}, template, o));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392