简体   繁体   English

在json中使用id查找对象索引

[英]find the object index using id in json

I have a json that contains many objects: 我有一个包含许多对象的json:

[Object, Object, Object, ... ]

Inside each object there is an object number and an id: 在每个对象内部都有一个对象编号和一个id:

0: Object
id: "theObjectImLookingFor"
...

How can I find the object number (0) using the id "theObjectImLookingFor" in javascript? 如何在javascript中使用id“theObjectImLookingFor”找到对象编号(0)?

Try this: 尝试这个:

function someFunc(){
    var objArr = [Object, Object, Object, ... ];
    for(var i = 0; i < objArr.length; i++){
         if(objArr[i].id == "theObjectImLookingFor")
            return i;
    }
    return "No value matched";
}

This assumes there's only one property with a numeric name. 这假设只有一个带有数字名称的属性。 This is a very strange way to store something you want to be able to look up. 这是一种非常奇怪的方式来存储您想要查找的内容。 Why not give each object an obj_number property? 为什么不给每个对象一个obj_number属性?

function find_object(json, str) {
    for (var i = 0; i < json.length; i++) {
        if (json[i].id == str) {
            for (var key in json[i]) {
                if (IsNumeric(key)) {
                    return key;
                }
            }
        }
    }
    return false; // Not found
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM