获取数组中对象的数组中的对象索引

时间:2014-04-03 06:50:00

标签: javascript jquery arrays object impactjs

使用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没问题。

编辑: 游戏必须在移动设备上顺利运行,因此有一个有效的解决方案是好的。

4 个答案:

答案 0 :(得分:1)

试试这个,

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);
        }
    }
}

Live Demo

Updated demo

答案 1 :(得分:0)

您可以使用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"

答案 2 :(得分:0)

您可以创建一个函数来获取对象的索引以及其他对象,例如像

//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);

希望它可以帮助你开始!

答案 3 :(得分:0)

感谢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;
}

live here