1つには文字列値が含まれ、もう1つには整数値が含まれることを除いて、同様の値を持つ2つのオブジェクトがあります。
var ids = ["1", "5", "3"]
var items = [
{
id: 1
},
{
id: 2
},
{
id: 4
}
]
var items2 = [
{
id: 2
},
{
id: 4
}
]
私がやろうとしているのはid
、オブジェクトのいずれかのキーに。items
からの同じ値が含まれているかどうかを確認することids
です。したがって、ids
「1」が含まれていitems
て、1も含まれている場合id
、関数はtrueを返す必要があります。
これは私がこれまでに試したことです:
function checkIfValueExists(a, b) {
if (a.some(i => i.includes(b.toString))) {
console.log("value found")
return true
} else {
console.log("value not found")
return false
}
}
checkIfValueExists(ids, items) // should console.log("value found") and returns true
checkIfValueExists(ids, items2) // should return false
JavaScript / ES6を使用してこれを実現するにはどうすればよいですか?
あなたは、使用していることを行うことができますsome
とincludes
。some()
項目配列のonにメソッドを適用id
しtoString
、を使用includes
して各項目のを文字列に変換してから、を使用しids
ます。
var ids = ["1", "5", "3"];var items = [ { id: 1 }, { id: 2 }, { id: 4 }];var items2 = [ { id: 2 }, { id: 4 }];
const checkIfValueExists = (ids, items) => items.some(item => ids.includes(item.id.toString()))
console.log(checkIfValueExists(ids, items)) // should console.log("value found") and returns true
console.log(checkIfValueExists(ids, items2)) // should return false
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加