Sort array by first coming the object

Asked

Viewed 53 times

0

I have an object that returns array and object at the same time Example: inserir a descrição da imagem aqui

I was able to retrieve the object by calling straight

var obj = { name: obj.name, month: obj.month, year: obj.year }

You can sort this array to first bring the object before the array ?

Example :

objeto,
  [0] objeto,
  [1] objeto,
  [2] objeto

Note that in the image it retrieves the object last

  • Your question seems too vast How To Ask try edit your question, putting the code can help to find the problem

  • 1

    This object is strange... what gives console.log(JSON.stringify(obj));?

  • This looks like an array in which you also created keys like the name and year and so it gets complicated. How this information is built ?

1 answer

1


It is not possible to do what you ask. On an object, all properties that has key numerical are placed up and drawn automatically, even if you create the object originally with them "below":

const myObject = {
  name: "Geral",
  age: null,
  // Note que as propriedades com chave numérica estão no final:
  0: {
    name: "Foo"
  },
  1: {
    name: "Bar"
  }
}

// Note agora, no log do console, que as propriedades com chave
// numéricas estarão no início do objeto.
console.log(myObject)

What can you do?

In this case, you can create a function that transforms this object into a array of arrays key-value. Something like that:

function sortObjectItems(o) {
  const normalKeys = []
  const numericKeys = []

  for (const [key, val] of Object.entries(o)) {
    // Caso a chave da propriedade da iteração atual for um valor numérico:
    if (/^\d+$/.test(key)) {
      numericKeys.push([parseInt(key, 10), val])
    // Caso a chave da propriedade da iteração atual não for um valor numérico:
    } else {
      normalKeys.push([key, val])
    }
  }

  // Concatenamos os dois arrays criados e retornamos eles:
  return [...normalKeys, ...numericKeys]
}

const sortedArray = sortObjectItems({
  0: { name: 'Foo', age: 1 },
  1: { name: 'Bar', age: 2 },
  name: 'Baz',
  age: 3
})

console.log(sortedArray)

In the above example, you will always receive something like:

[[key, value], [key, value] ...]

Given the behavior of the object in Javascript, I think this is the best solution to your problem.

Reference:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.