我有json数据,我正在推动一个数组。我需要获取某个ID值的索引值。我尝试过IndexOf,但似乎没有用。
我附上了我的代码和数组的片段。以及指向您使用的JSON文件的链接。
我添加了评论以突出显示问题区域。我还发送了数组的截图,其中包括console.logged以及我需要得到的值。
var posts;
var imgTitle;
var imgLink;
var url = 'http://www.capetownetc.com/api/get_category_posts/?slug=';
var counter = 1;
var postID;
var callFunction = true;
var articleContent;
var titleMaxLength = 28;
var articleArray = [];
var topicName = 'news';
var pageNumber;
var linkID;
//POST CARDS
function postCards(pageNumber, cardLimit, container, topic) {
topicName = topic || 'news';
pageNumber = pageNumber || 1;
$.ajax({
type: 'GET'
, url: url + topicName + '&count=10&page=' + pageNumber
, data: {
get_param: 'value'
}
, dataType: 'jsonp'
, success: function postPop(data) {
$('.main-content').append('<div class="card-container card-container' + container + '"></div>');
$.each(data.posts, function(i){
posts = data.posts[i];
imgTitle = data.posts[i].title;
imgLink = data.posts[i].thumbnail_images.medium.url;
imgTitle = imgTitle.substr(0, titleMaxLength);
postID = data.posts[i].id;
$('.card-container' + container).append('<a href="' + postID + '" class="article-link" onclick="postArticle(' + i + ',' + pageNumber +')"><div class="card card1"><img src="' + imgLink + '" class="card-img"><span><h2 class="card-heading">' + imgTitle + '</h2></span></div></a>');
$('#loading').css('opacity' , '0');
callFunction = true;
//JSON CONTENT TO ARRAY
articleArray.push(posts);
//**PROBLEM AREA - I need to get the ID position of the posts in this array, see screenshot -
if(window.location.hash) {
mainView.router.load({
content: newPageContent,
animatePages: true
});
articleContent = articleArray[i].content;
$('.article-container').html(articleContent);
console.log('hash');
}
else {
}
});
console.log(articleArray);
}
}).done(function(){
myApp.hidePreloader();
});
myApp.showPreloader();
}
postCards(counter, 10, counter);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="main-content">
</div>
答案 0 :(得分:1)
如果你想通过ID获取特定项目的索引,那么首先你需要通过ID获取项目对象,然后你可以使用indexOf来获取该特定项目的索引。
var item = yourArray.find(function (e) {
if (e.id == "your Id") {
return e;
}
});
var index = yourArray.indexOf(item);