NodeJS:break Array.some循环

时间:2017-04-10 13:13:12

标签: javascript arrays json node.js

我有以下函数接收JSON数组模板并返回JSON对象。

代码执行console.log。但是,它始终在函数末尾返回null。有什么想法吗?

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

模板数组

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

但是,它始终返回null。

1 个答案:

答案 0 :(得分:0)

这是工作示例,

使用.find代替.some。我们总是希望得到一个对象。



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));




相关问题