简体   繁体   中英

How do I select an item out of a JavaScript array when I only know a value for one of the item's properties?

I have the following JavaScript object:

{
    "DPI": "66.8213457076566",
    "width": "563.341067",
    "editable": "True",
    "pricecat": "6",
    "numpages": "2",
    "height": "400",
    "page": [{
        "filename": "999_9_1.jpg",
        "line": [{
            "test": "test 1",
            lineid: 22
        },
        {
            "test": "test 2",
            lineid: 22
        },
        {
            "test": "test 3",
            lineid: 22
        },
        {
            "test": "test 4",
            lineid: 22
        },
        {
            "test": "blank",
            lineid: 22
        }]
    },
    {
        "filename": "999_9_2.jpg",
        "line": []
    }]
}

I can do most things with lines like measurements.page[0].line[0].lineid;

But what I am really stuck with is when I want to edit a specific line but I only have the lineid value available (for example 22 ) and not the line number in the array:

measurements.page[0].line[WHAT DO I PUT HERE].test = "new changed value";

you have to search

function find_in_array(arr, name, value) {
    for (var i = 0, len = arr.length; i<len; i++) {
        if (name in arr[i] && arr[i][name] == value) return i;
    };
    return false;
}

var id = find_in_array(measurements.page[0].line, 'lineid', 22);

您需要使用for循环遍历数组for直到找到您要查找的项目。

You can create a function to do this:

function getLinesByLineID( lines, id ) {
   var results = [];
   for( var i = 0, j = lines.length; i < j; i++ ) {
       if( lines[ i ].lineid === id ) {
          results.push( lines[ i ] ); 
       }
   }
   return ( results.length > 0 ) ? results : false;
}

You can then call it like this: var lines = getLinesByID( json.page[0].line, 22 ) ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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