如何通过键从 JavaScript 字典数组中获取对象?

How do you get an object from an array of JavaScript dicts by key?

我希望我使用的是正确的术语...我通常是一个 Python 人,所以我习惯了字典数据类型。不管怎样,我现在正在开发一个 Node 应用程序,我 运行 遇到了一个问题。我有一个下拉菜单中的用户 select,该菜单是通过传递给 EJS 的字典对象数组填充的。每个对象都有一个 slug 和一个名称。所以,它会是这样的:

const computers = [{slug: 'dell-desktop', name: 'Dell Desktop'}, {slug: 'macbook-pro', name: 'MacBook Pro'}, {slug: 'imac-27-inch', name: 'iMac, 27-Inch'}];

我使用名称填充表单,但我需要在后端使用 URL 的 slug。所以它看起来像这样:

app.get('/form', function(req, res){
res.render('form.ejs', {computers: computers});
});

总的来说,一切似乎都运行良好,表单按预期填充:

<select id = 'computer' name = 'computer'>
        <% for (var i = 0; i<computers.length; i++) { %>
          <option value = '<%= computers[i].slug %>'><%= computers[i].name %></option>
          <% } %>
        </select>

但是,我从表单收到的数据只是提供了 slug。我的问题是,有没有一种好的方法可以使用 slug 键从字典数组中获取名称?我这样试过,还是不行,不知道是不是因为他们在一个数组里?

app.post('/form', function(req, res){
  var c_slug = req.body.computer;
  var name = computers[c_slug];
  console.log(c_slug);
  console.log(name);
  res.send('Success!')
});

我无法在搜索中找到与此相关的任何内容。我找到了一个映射解释,但是它获取了给定键的所有值。我希望我遗漏了一些明显的东西!

您可以使用 Array.find() 方法在数组中查找符合给定条件的元素。

It returns the value of the first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.

app.post('/form', function(req, res){
  const c_slug = req.body.computers;
  const element = computers.find(el => el.slug === c_slug);
  // element is either an element that was found or undefined
  if (element) {
     const name = element.name;
     // the above can be written like this in ES6
     // const { name } = element;

     // do something
  } else {
     // return 400 (Bad Request)
  }
...

P.S. 我正在使用 const instead of var which is ES6 syntax and arrow function () => ...。两者都可以在 NodeJS 8+ 的服务器端使用。

你可以使用 .find() 方法

app.post('/form', function(req, res){
  var c_slug = req.body.computers;
  var computer = computers.find(el => el.slug === c_slug);
  console.log(c_slug);
  console.log(computer.name);
  res.send('Success!')
});

或者您可以手动查找

app.post('/form', function(req, res){
  var c_slug = req.body.computers;
  var name ;   
  for (let i = 0; i < computers.length; i++) {
    if (computers[i]['slug'] === c_slug) {
      name = computers[i]['slug'];
      break;
    }
  }
  console.log(c_slug);
  console.log(name);
  res.send('Success!')
});