【问题标题】:Javascript check if an id is present in an array of objects [duplicate]Javascript检查对象数组中是否存在id [重复]
【发布时间】:2021-02-19 10:41:41
【问题描述】:

这是我的数组:

[{id: 1, value:'blabla'}, {id: 2, value:'blabla'}, {id: 3, value:'blabla'}]

如果此数组中存在 id,我会尝试返回 true 或 false:

array.includes(2) -> true
array.includes(7) -> false

我需要对数组的每个对象的 id 索引执行此操作。

我知道我可以在数组的每个 id 上使用 foreach,但我想使用最简洁的方式来执行此操作。 我可以用什么?谢谢!

【问题讨论】:

标签: javascript arrays object


【解决方案1】:

在给定的数组上直接操作Array.prototype.some,可以写...

array.some(({ id }) => id === yourID)

... 或者使用更通用的方法,例如 ...

var array = [
  { id: 1, value: 'blabla' },
  { id: 2, value: 'blabla' },
  { id: 3, value: 'blabla' },
];

function hasItemWithKeyAndValue(arr, key, value) {
  return arr.some(item => item[key] === value);
}

// what the OP did ask for.
console.log(
  "hasItemWithKeyAndValue(array, 'id', 1) ?",   // true
  hasItemWithKeyAndValue(array, 'id', 1)
);
console.log(
  "hasItemWithKeyAndValue(array, 'id', '1') ?", // false
  hasItemWithKeyAndValue(array, 'id', '1')
);
console.log(
  "hasItemWithKeyAndValue(array, 'id', 3) ?",   // true
  hasItemWithKeyAndValue(array, 'id', 3)
);
console.log(
  "hasItemWithKeyAndValue(array, 'id', 4) ?",   // false
  hasItemWithKeyAndValue(array, 'id', 4)
);

// proof of the generic key value approach.
console.log(
  "hasItemWithKeyAndValue(array, 'value', 'blabla') ?", // true
   hasItemWithKeyAndValue(array, 'value', 'blabla')
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

【讨论】:

  • 试试这个 array.some(item => item.id === yourID) @Tony S
  • 最简洁的方式是array.some(({id}) => id === yourId)
【解决方案2】:

你可以使用Array.some():

let arr = [{id: 1, value:'blabla'}, {id: 2, value:'blabla'}, {id: 3, value:'blabla'}];
arr.some(e => e.id === 1);
// -> true

如果您想要像 Array.includes() 这样的方法,您可以扩展 Array 原型:

let arr = [{id: 1, value:'blabla'}, {id: 2, value:'blabla'}, {id: 3, value:'blabla'}];

Array.prototype.hasId = function(id){
    return this.some(e => e.id === id);
};

console.log(arr.hasId(1));
console.log(arr.hasId(3));
console.log(arr.hasId(4));

否则我就把它包装在一个函数中:

let arr = [{id: 1, value:'blabla'}, {id: 2, value:'blabla'}, {id: 3, value:'blabla'}];


let hasId = function(arr, id){
    return arr.some(e => e.id === id);
};

console.log(hasId(arr, 1));
console.log(hasId(arr, 2));
console.log(hasId(arr, 4));

【讨论】:

    猜你喜欢
    • 2021-04-22
    • 2022-07-20
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    相关资源
    最近更新 更多