Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

94
Visualizações
Convert string of co-ordinates to nested objects x and y

I have the following string: area = "73,159,160,178,165,340,70,382"; And I need to convert it to the following format:

area = [
{
"x": 73,
"y": 159,
},
{
"x": 160,
"y": 178,
},
{
"x": 165,
"y": 340,
},
{
"x": 70,
"y": 382,
}
]

I can start by converting it to a normal array:

JSON.parse("[" + area + "]")

But I'm now stuck on how to make the nested objects. How would I now know what is every other odd and even number and allocate it to the corresponding object?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can split the string by a comma and use a for loop to loop through the resulting array and construct the objects:

const str = "73,159,160,178,165,340,70,382"

const split = str.split(",")
const arr = []

for(let i = 0; i < split.length; i++){
  arr.push({"x":split[i], "y":split[++i]})
}

console.log(arr)

about 4 years ago · Juan Pablo Isaza Relatório

0

Here is an alternative using regex

let area = "73,159,160,178,165,340,70,382"

let regex = /\d+,\d+/g

match = area.match(regex).map(match => {
  let [x, y] = match.split(",")
  return {x, y}
})

console.log(match)

about 4 years ago · Juan Pablo Isaza Relatório

0

I believe this is what you are trying to achieve? please note that I didn't add a code to check if the number of item In the array will be even or not, so if your newArea is odd this function will fail

function Convert(arrayOfArea){
    let Converted = [];
  let count = arrayOfArea.length/2;
  let mod = arrayOfArea.length%2;
  
  for(let i = 0; i < count; i++){
    Converted.push({x:0 , y:0});
    Converted[i].x = arrayOfArea[i]
    Converted[i].y = arrayOfArea[i+1];
  }
  return Converted;
}

let strArea = "73,159,160,178,165,340,70,382";
let newArea = JSON.parse("["+strArea+"]");
console.log(Convert(newArea));

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda