如果对象键等于预定义的值,我如何附加json数据

How can I append json data if object key is equal to a predefined value?

本文关键字:何附加 数据 json 对象 预定义 如果      更新时间:2023-09-26

我收到一个ajax GET请求,它通过循环拉入数据。我试图实现的是获得相关的帖子,但不在当前帖子的预定义id值中。所以我有下面的功能:

var _permId = $('#work-area').data('current-id');    
var getRelatedPosts = function() {
            $.ajax({
              url: '/wp-json/posts?type=case-studies&filter[taxonomy]=awards&filter[term]='+_awardsPart+'',
              success: function ( query ) {
                //List some global variables here to fetch post data
                // We use base as our global object to find resources we need
                // _permId is the var that tells me the current id of this post
                var posts = query;
                postFull = [];
                for(var i = 0; i < posts.length; i++) {
                    //terms.push(term);
                    var postObject = posts[i];
                    postFull.push(postObject);
                    for (var key in postObject) {
                        //console.log(postObject[key]);
                        if (postObject[key] === _permId)  {
                            console.log('this is the same as this post');
                        }
                    }
                };
              },
              cache: false
            });
        };

如果post对象id与_permId的值相同,我想做的是不允许任何内容通过。

以下是用键和值检索json的一个想法:

Object {ID: 4434, title: "new brand case", status: "publish", type: "case-studies", author: Object…}

ID是我要针对其设置参数的值。

如果您只想检查ID:,就不必在对象上循环

...
postFull = [];
for(var i = 0; i < posts.length; i++) {
    var postObject = posts[i];
    postFull.push(postObject);
    if(postObject.ID === _permId) {
        //they have the same id
    }
};

编辑:要获得您想要的数据,您可以使用$.grep:

var newArray = $.grep(posts, function(e, i){return e.ID !== _permiId;});

或纯JS

var newArray = [];
for(var i = 0; i < posts.length; i++){
    var p = posts[i];
    if(p.ID !== _permId){
        newArray.push(p);
    }
}