在Console中记录匹配对象

时间:2018-02-20 21:09:46

标签: javascript arrays

目前我正在使用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": ""
  }
}]
};

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

1 个答案:

答案 0 :(得分: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>
&#13;
&#13;
&#13;