0

I have an object that receives coordinates values ​​like this

Object{
[key]:[value],
[key]:[value],
}

Each key is a coordinate x,y and each value is a true boolean. I generate the coordinates through a program that receives an array with values ​​0 for true and 1 for false, a width and a height.

I want to output each key as a coordinate x,y inside that object in this way:

Object{
[gridCoords([0, 0, 0, 0,
             1, 1, 0, 1,
             0, 0, 0, 0,
             0, 0, 0, 0],
             4,
             4)]:true,
}

So, my function is something like this:

function gridCoords(data, height, width)  {
  var obj = [];
  for (let row = 0; row < height; row++) {
    for (let col = 0; col < width; col++) {
      let key=`${row * 16},${col * 16}`
      let value= (data[row * height + col] === 1 ? true: false )
      if (value){
        obj.push(key)
      }
    }
  }
  return obj
}

But i received this:

{
16,0,16,16,16,48,32,16,32,32: true
}

Instead of:

{
16,0: true,
16,16: true,
16,48: true,
32,16: true,
32,32: true
}

What I can do?

1 Answer 1

2

I think you want an object not an array here:

function gridCoords(data, height, width)  {
  var obj = {};
  for (let row = 0; row < height; row++) {
    for (let col = 0; col < width; col++) {
      let key=`${row * 16},${col * 16}`
      let value= (data[row * height + col] === 1 ? true: false )
      if (value){
        obj[key] = value
      }
    }
  }
  return Object.keys(obj)
}
Sign up to request clarification or add additional context in comments.

5 Comments

You are right!!! But that returns me [key]:[value] and i want only the keys, because the [value] is already in the main object. Will be possible?
You can return the object with only the keys by calling Object.keys
Thanks. The thing is that still output me this { 16,0,16,16,16,48,32,16,32,32: true} in the object where i call the function.
Don't call Object.keys on the return value and don't wrap the function call in another object
Just call it like so gridCoords([0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], 4,4)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.