簡體   English   中英

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.

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