簡體   English   中英

如何檢查對象數組中是否存在id值

[英]How to check if an id value exists in an object array

給定對象{id:“ x”,title:“ title”}的數組“ posts”,我需要在輸入新帖子 (通過id是字段的表單) 之前驗證是否存在先前輸入的id

我嘗試遍歷帖子,但是在輸入重復的新數據時會引起問題。 謝謝您的幫助,這讓我發瘋了。

// ADD NEW POST FROM FORM TO ARRAY
$("#form").submit(function(event) {
    event.preventDefault();
    var id = Number($("#idPost").val());
    var title = $("#titlePost").val();
    var date = new Date($("#data").val());
// CHECK IF id ALREADY EXISTS, IF YES, BLOCK ENTRY    
    for(num of posts){
        console.log (id, num.id);
        if(id === num.id){ 
            console.log("error");
        } else {
            var post = new Post(id, title, date);
        }                
    };      
});

正如@Andreas建議的那樣,您可以使用Array.Some()查找數組中是否存在元素。

 var found = posts.some(el => el.id  === id ); // It returns true if id exist in an array
 if(found)
 {
  //Your codes here
 }

或者,您可以嘗試使用Array.Filter()來查找元素是否存在於數組中。

var found = posts.filter(el => el.id === id).length > 0; // .length returns 1 if id exist in an array
if(found)
{
   //Your code goes here
}

您可以嘗試Array.find()Array.IndexOf()執行相同的操作

以下使用Array.Some()

 //Lets consider below is the value in posts arry var posts = [ { id: 1, username: 'foo' },{ id: 2, username: 'bar' } ]; var newObj = {"id": 3, "username": 'prasad'}; //console.log(posts); var found = posts.some(el => el.id === 2 ); if(found) { for(num of posts){ //console.log (3, num.id); if(4 === num.id){ //Your code //console.log("error"); } else { //Your code //console.log(num); } }; posts.push(newObj); console.log(posts); } 

您可以按照Andreas的建議使用Array.prototype.some()或使用Array.prototype.find()

Array.prototype.some()只會返回true或false,不會返回匹配的對象。 如果需要該對象,請使用find(),如下所示:

$("#form").submit(function(event) {
event.preventDefault();
var id = Number($("#idPost").val());
var title = $("#titlePost").val();
var date = new Date($("#data").val());
var objectPresent = posts.find(function(post) {
   return post.id === id;
});
if(!objectPresent) {
   var post = new Post(id, title, date);
} else {
  console.log(objectPresent.id,"is already taken up by ", objectPresent.title);
}

});

我認為您應該使用JSON對象,它將幫助您輕松識別,如何識別,密鑰是否存在於JSON對象列表中

JSON_Object.hasOwnProperty(ID)

var x = {};
x[1] = "{'title1':'title1'}";
x[2] = "{'title2':'title2'}";
x[3] = "{'title3':'title3'}";

if(x.hasOwnProperty(1)){
 console.log('value present');
}

if(x.hasOwnProperty(5)){
 console.log('value not present');
}

這可能對您有幫助。

這只是解決問題的一種方法。 使用這個,以后再謝謝我,:)

這應該工作:

if (postExists(posts, id)){
    // invlaid post entry
} else {
    // add new post
}

function postExists(posts, id) {
    return posts.some(function(post){
        return post.id == id;
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM