【问题标题】:Log matching objects in Console [duplicate]在控制台中记录匹配对象 [重复]
【发布时间】:2018-07-31 08:17:53
【问题描述】:

目前我正在使用 JavaScript 对象,如果在团队数组中找到一个人的 ID,则在控制台中记录匹配项。

var employees = {
  "team1": [3,0],
  "team2": [1,2],
  "people": [{
    "id": 0,
    "name": "John",
    "description": "test test test",
    "img": ""
  }, {
    "id": 1,
    "name": "Adam",
    "description": "this is a test",
    "img": ""
  }, {
    "id": 2,
    "name": "Fred",
    "description": "fjdk;sf;lsd,;fl,s;l",
    "img": ""
  }, {
    "id": 3,
    "name": "Bill Murray",
    "description": "fndsjlfnlskdm",
    "img": ""
  }
}]
};

实现这一目标的最佳方法是什么?我知道这是一个模糊的问题,但我担心,我被谷歌的漩涡所吸引,我认为我让自己变得比需要的更困难。如果有人对如何实现这一点有任何建议,我希望能在正确的方向上得到一些帮助。谢谢。

【问题讨论】:

  • 如果你使用正确的术语,谷歌可能会少得多。它是一个 javascript 对象,而不是一个 json 对象。
  • 你真正想做什么?标题说“排序”,但问题只是说记录匹配。
  • 您可能会在这里找到答案:stackoverflow.com/questions/979256/…
  • @Tanckom 尽管有标题,但他的问题似乎与排序无关。
  • 刚看到他改了标题。我想在这种情况下,这是用 forEach 和 indexOf 完成的

标签: javascript arrays


【解决方案1】:

尝试使用Array.filter

var employees = {
  "team1": [3, 0],
  "team2": [1, 2],
  "people": [{
      "id": 0,
      "name": "John",
      "description": "test test test",
      "img": ""
    }, {
      "id": 1,
      "name": "Adam",
      "description": "this is a test",
      "img": ""
    }, {
      "id": 2,
      "name": "Fred",
      "description": "fjdk;sf;lsd,;fl,s;l",
      "img": ""
    }, {
      "id": 3,
      "name": "Bill Murray",
      "description": "fndsjlfnlskdm",
      "img": ""
    }]
};


var id = 3;
var person = employees.people.filter(function(row){return row.id == id})[0] || "No one by that ID";
console.log(person)

奖励选项(只是为了好玩):使用Javascript Query Language

var employees = {
  "team1": [3, 0],
  "team2": [1, 2],
  "people": [{
      "id": 0,
      "name": "John",
      "description": "test test test",
      "img": ""
    }, {
      "id": 1,
      "name": "Adam",
      "description": "this is a test",
      "img": ""
    }, {
      "id": 2,
      "name": "Fred",
      "description": "fjdk;sf;lsd,;fl,s;l",
      "img": ""
    }, {
      "id": 3,
      "name": "Bill Murray",
      "description": "fndsjlfnlskdm",
      "img": ""
    }]
};

var id = 3;
jSQL.createTable("employees", employees.people).execute();
var person = jSQL.query("select * from employees where id = ?").execute([id]).fetch("ASSOC");
console.log(person);
<script src="https://pamblam.github.io/jSQL/scripts/jSQL.min.js"></script>

【讨论】:

  • 我怀疑这不是他要问的。如果是这样,您可以作为 https://stackoverflow.com/questions/20195958/how-to-find-object-in-array-by-property-in-javascript 的骗子关闭
  • 没有箭头函数你能不能修改最后一行?
  • @thelgloriouspast 副本中的答案显示了如何以多种不同的方式做到这一点。
  • @thelgloriouspast - 好的,确定
猜你喜欢
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 2021-04-13
  • 2020-07-30
  • 2017-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多