![](/img/trans.png)
[英]Check if each object in array of objects contains a value that is in another array (JavaScript)
[英]javascript array object value contains another array value
我有這樣的數組
"chapters":[
{
"_id": "5422c6ba0f6303ba22720e14",
"chapter_name": "Morbi imperdiet libero sed.",
"sub_title": "Nam id elit tincidunt amet.",
"mystatus": "noidea"
},
{
"_id": "5422bd0d5cb79ae6205b2f6a",
"chapter_name": "Donec id accumsan volutpat.",
"sub_title": "Cras volutpat velit nullam.",
"mystatus": "noidea"
},
{
"_id": "5423ea5f17c83ad41da1765e",
"chapter_name": "Donec id accumsan volutpat.",
"sub_title": "Cras volutpat velit nullam.",
"mystatus": "noidea"
}
],
我還有一個
"currentstat": [
"5423ea5f17c83ad41da1765e",
"5422c6ba0f6303ba22720e14",
"5422bd0d5cb79ae6205b2f6a"
],
我想檢查在chapters._id
包含的currentstat
數組值。
我嘗試過這樣。
for (var i = 0; i < chapters.length; i++) {
var attenId = currentstat.toString();
if (attenId.indexOf(chapters[i]._id) != -1) {
}
}
沒有我我無法得到結果
var attenId = currentstat.toString();
我還需要一件事。
我需要根據currentstat
數組值將這些status
數組值分配給相應的chapters
數組。
status: [ 'passed', 'passed', 'attending']
整個代碼是這樣的
for (var i = 0; i < chapters.length; i++) {
var attenId = currentstat.toString();
if (attenId.indexOf(chapters[i]._id) != -1) {
allChapters[i].mystatus = (status[i]) ? status[i] : 0;
}
}
但該值未分配給相應的_id
請幫助!
例:
var currentstat = ["1","2","3"];
var chapters = [{_id:"2"}, {_id:"4"}, {_id:"6"}];
var objects = chapters.filter(function(chapter) {
return ~currentstat.indexOf(chapter._id);
});
只需用您的數據替換這些數組, objects
將包含具有相同id的對象(在此特定示例中為[{_id:"2"}]
。
最粗略的方法是2個for循環,一個在另一個循環內:
for (var i = 0; i < currentstat.length; i++) {
for (var j = 0; j < chapters.length; j++) {
if (currentstat[i] === chapters[j]._id){
alert('found it at: ' + i + ' ' + currentstat[i]);
}
}
}
檢查這個小提琴
粗略的方法是:
for (var i = 0; i < chapters.length; i++) {
if (currentstat.indexOf(chapters[i]._id) >= 0) {
alert('found ' + currentstat[i] + ' at index ' + i);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.