javascript - 在 json 数组中搜索

标签 javascript arrays json

我是 json 新手。我的 json 数组

[{"seat_number":"834"},{"seat_number":"8F3"},{"seat_number":"891"},
{"seat_number":"814"},{"seat_number":"4081"},{"seat_number":"8F1"},
{"seat_number":"8F9"},{"seat_number":"4039"},{"seat_number":"0"},
{"seat_number":"509"},{"seat_number":"662"},{"seat_number":"561"},
{"seat_number":"791"},{"seat_number":"849"}]

我想查找数组中已存在的座位号。

if(($scope.employeeSeat.seat_array.indexOf($scope.employeeData.new_seat_number))>-1)
{
alert('Seat number is already assigned.Please Check');
} 

出了什么问题?

最佳答案

如果你愿意,你可以用困难的方式做到这一点

var data = [
  {"seat_number":"834"},{"seat_number":"8F3"},
  {"seat_number":"891"},{"seat_number":"814"},
  {"seat_number":"4081"},{"seat_number":"8F1"},
  {"seat_number":"8F9"},{"seat_number":"4039"},
  {"seat_number":"0"},{"seat_number":"509"},
  {"seat_number":"662"},{"seat_number":"561"},
  {"seat_number":"791"},{"seat_number":"849"}
];

function matchingSeat(x) {
  return data.some(function(elem) {
    return elem.seat_number === x;
  });
}

console.log("831", matchingSeat("834")); // 834 true
console.log("8F3", matchingSeat("8F3")); // 8F3 true
console.log("999", matchingSeat("999")); // 999 false

我认为这太痛苦了。一旦您掌握了一些可重用的实用函数,这个问题就变得更容易解决。

Don't freak out: the ES5 solution is below

// ES6
// reusable lib
let prop = y => x => x[y];

let comp = f => g => x => f(g(x));

let eq = y => x => x === y;

let some = f => xs => xs.some(f);

现在编写一些助手来解决您的任务

let eqSeat = x => comp(eq(x))(prop("seat_number"));
let hasSeat = comp(some)(eqSeat);

检查一下

console.log("831", hasSeat("834")(data)); // 831 true
console.log("8F3", hasSeat("8F3")(data)); // 8F3 true
console.log("999", hasSeat("999")(data)); // 999 false
<小时/>

这是 ES5 中的相同代码

// ES5
// reusable lib
var prop = function prop(y) {
  return function (x) {
    return x[y];
  };
};

var comp = function comp(f) {
  return function (g) {
    return function (x) {
      return f(g(x));
    };
  };
};

var eq = function eq(y) {
  return function (x) {
    return x === y;
  };
};

var some = function some(f) {
  return function (xs) {
    return xs.some(f);
  };
};

你的 helper

var eqSeat = function eqSeat(x) {
  return comp(eq(x))(prop("seat_number"));
};

var hasSeat = comp(some)(eqSeat);

尝试一下

console.log("831", hasSeat("834")(data)); // 831 true
console.log("8F3", hasSeat("8F3")(data)); // 8F3 true
console.log("999", hasSeat("999")(data)); // 999 false

关于javascript - 在 json 数组中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30450915/

相关文章:

javascript - 在 $stateParams url 中传递对象

javascript - Spring MVC Controller 不拦截 Ajax POST

javascript - 在 CRM 2011 中使用 OData 检索多个

python - Pandas .read_json(JSON_URL)

arrays - Swift 数组类型现在使用多维数组的元素类型用括号括起来

json - 解析 api 响应 JSON 以获取内容值

javascript - Highcharts柱状系列点对象点击功能

javascript - 在 WordPress 中链接外部 JS 和 CSS 文件

C++ 负数组索引

c - 致命运行时错误 - C 函数