0

I have the following function that receives a JSON array templates and returns a JSON object.

The code executes the console.log. However, it always returns the null at the end of the function. Any ideas?

function getTemplate(templates, myId) {
  Object.keys(templates).some(obj => {
    if (templates[obj].id === myId) {
      console.log('HELLO');
      return templates[obj];
    }
  });
  return null;
}

template array

[
    {
        "id": 80,
        "name": "template 1"
    },
    {
        "id": 81,
        "name": "template 2"
    }
]

However, it always returns null.

1 Answers1

-1

Here is working example,

use .find instead of .some. We always expect to get one object.

function getTemplate(templates, myId) {
  return templates.find(template => template.id === myId);
}

var array =
[
    {
        "id": 80,
        "name": "template 1"
    },
    {
        "id": 81,
        "name": "template 2"
    }
]
console.log(getTemplate(array, 80));
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
loelsonk
  • 3,570
  • 2
  • 16
  • 23