如何检查对象数组中是否存在id值

时间:2019-05-26 17:13:18

标签: javascript

给出对象{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);
        }                
    };      
});

4 个答案:

答案 0 :(得分:1)

按照@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);
 }

答案 1 :(得分:1)

您可以按照Andreas的建议使用 Array.prototype.some(),也可以使用 Array.prototype.find()

Array.prototype.some()只会返回true或false,不会返回匹配的对象。 如果需要该对象,请按以下方式使用find():

// ignore notification {}
data {
    "type" : "message",
    "id_message" : res
}
to: key

});

答案 2 :(得分:0)

我认为您应该使用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');
}

这可能会对您有所帮助。

这只是解决问题的一种方法。 使用这个,以后再谢谢我,加油:)

答案 3 :(得分:0)

这应该有效:

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

function postExists(posts, id) {
    return posts.some(function(post){
        return post.id == id;
    });
}
相关问题