簡體   English   中英

獲取數組中對象的索引

[英]get index of object in array in object in array

與游戲引擎Impactjs一起使用時,此處和關卡的設置非常奇怪:

[
    {
       "entities": [
            {"type":"type1","x":100,"y":100,"settings":{"directsTo":"-5"}},
            {"type":"type2","x":101,"y":101,"settings":{"directsTo":"-4"}}
        ],
        "layer": [
            other data
         ]
    }
]

我想知道如何根據設置對象的directsTo屬性獲取type1對象的索引?

Javascript或jQuery都可以。

編輯:游戲必須在移動設備上流暢運行,因此擁有高效的解決方案是不錯的。

嘗試這個,

var arr =[{
    "entities": [{
        "type": "type1",
        "x": 100,"y": 100,
        "settings": {"directsTo": "-5"}
    }, {
        "type": "type2",
        "x": 101,"y": 101,
        "settings": {"directsTo": "-4"}
    }],
    "layer": ['other data']
}];
var t='type1';
var newArr=arr[0];
for(var data in newArr){
    for(a in newArr[data]){
        if(newArr[data][a].type == t){
             alert('Index of '+t+' is '+a+' in '+data);
        }
    }
}

現場演示

更新的演示

您可以使用filter屬性嗎?

假設您的JS對象看起來像這樣

var j = [
    {
       "entities": [
            {"type":"type1","x":100,"y":100,"settings":{"directsTo":"-5"}},
            {"type":"type2","x":101,"y":101,"settings":{"directsTo":"-4"}}
        ],
        "layer": [
            "otherdata":{}
         ]
    }
];

您可以使用找到對象

var result = j[0].entities.filter(function(n) { return n.settings.directsTo == "-5"; });
// result[0].type == "type1"

您可以創建一個函數來獲取其他對象之間的對象索引,例如這樣

//assuming you have the data parsed as a JSON object "data"
//and you also have your entity object as "obj"
function getIndex(obj, data){
    return data.entities.indexOf(obj);
}

如果沒有“ obj”對象,則必須創建一個函數,該函數首先根據屬性(例如類型參數)找到正確的對象

function findEntity(type, source){
    for(var i=0; i<source.entities.length; i++){
        if(source.entities[i].type == type){
            return source.entities[i];
        }
    }
    return false;
}

現在你可以這樣稱呼它

getIndex(findEntity("type1", data), data);

希望它可以幫助您開始!

感謝Rohan Kumar和ВикторНовиков。

var array =[
    {
        "entities": [
            {
                "type": "type1",
                "x": 100,"y": 100,
                "settings": {"directsTo": "-5"}
            },
            {
                "type": "type2",
                "x": 101,"y": 101,
                "settings": {"directsTo": "-4"}
            }
        ],
        "layer": ['other data']
    }
];

function getArrayIndexForLocationKey(arr, val) {
    for(var i = 0; i < arr.length; i++){
        if(arr[i].settings.directsTo == val)
            return i;
    }
    return -1;
}

住在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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