2015-04-29 11 views
14

ottengo sotto Array di oggetti JSON da JSPtrovare un valore all'interno della matrice JSON dell'oggetto

"Titles":[       
    { 
    "Book3" : "BULLETIN 3" 
    } 
    , 
    { 
    "Book1" : "BULLETIN 1" 
    } 
    , 
    { 
    "Book2" : "BULLETIN 2" 
    }  
] 

Sul lato JS, si analizza e vedo un array con 3 oggetti. Ora, voglio trovare/identificare un valore quando passo la chiave String.

Ad es. quando passo "Book2" dovrei ottenere il valore "BULLETIN 2". Qualcuno può aiutarmi a identificare l'approccio?

risposta

8

Prova questo

var data = { 
 
    "Titles": [{ 
 
     "Book3": "BULLETIN 3" 
 
    }, { 
 
     "Book1": "BULLETIN 1" 
 
    }, { 
 
     "Book2": "BULLETIN 2" 
 
    }] 
 
}; 
 

 
function getValueByKey(key, data) { 
 
    var i, len = data.length; 
 
    
 
    for (i = 0; i < len; i++) { 
 
     if (data[i] && data[i].hasOwnProperty(key)) { 
 
      return data[i][key]; 
 
     } 
 
    } 
 
    
 
    return -1; 
 
} 
 

 
console.log(getValueByKey('Book2', data.Titles));

1

Creiamo una funzione per ottenere un oggetto in una matrice per questo, che prende due argomenti: l'array e la chiave della proprietà che si desidera ottenere :

function getObjectInArray(arr, key) {  
    for (var i = 0; i < arr.length; i++) { 
     if (arr[i].hasOwnProperty(key)) return arr[i][key]; 
    } 
} 

Questo esegue il ciclo di ciascun oggetto alla ricerca di quella chiave specifica.


Soluzione: Ora si potrebbe fare qualcosa di simile getObjectInArray(titlesJSONArray, "Book2") e dovrebbe tornare "BOLLETTINO 2".

var titlesJSONArray = [ { "Book3": "BULLETIN 3" }, ... ]; // and so on 
var book2 = getObjectInArray(titlesJSONArray, "Book2"); // => "BULLETIN 2" 
4

Avere:

var x = [{ 
    "Book3" : "BULLETIN 3" 
}, { 
    "Book1" : "BULLETIN 1" 
}, { 
    "Book2" : "BULLETIN 2" 
}]; 

e

var key = "Book1"; 

È possibile ottenere il valore utilizzando:

x.filter(function(value) { 
    return value.hasOwnProperty(key); // Get only elements, which have such a key 
}).shift()[key]; // Get actual value of first element with such a key 

Si noti che che sarà un'eccezione, se oggetto doesn avere una tale chiave definita.

Inoltre, se ci sono più oggetti con tale chiave, questo restituisce solo il primo. Se avete bisogno di ottenere tutti i valori da oggetti con tale chiave, si può fare:

x.filter(function(value) { 
    return value.hasOwnProperty(key); // Get only elements, which have such a key 
}).map(function(value) { 
    return value[key]; // Extract the values only 
}); 

questo vi darà un array contenente solo i valori appropriati.

Inoltre, se si sta utilizzando jQuery, è possibile utilizzare grep invece di filter:

jQuery.grep(x, function(value) { 
    return value.hasOwnProperty(key); 
}) /* and so on */; 
3

Per raggiungere questo obiettivo, è necessario scorrere le chiavi e il test di elementi dell'array se il parametro chiave esiste nel array, se così ottenere il suo valore:

var jsonTitles = [       
 
      { "Book3" : "BULLETIN 3" }, 
 
      { "Book1" : "BULLETIN 1" }, 
 
      { "Book2" : "BULLETIN 2" }  
 
     ] 
 

 
    function getValue(key, array) { 
 
     for (var el in array) { 
 
      if (array[el].hasOwnProperty(key)) { 
 
       return array[el][key]; 
 
      } 
 
     } 
 
    } 
 

 
alert(getValue("Book1", jsonTitles));

W e utilizzare element[key] dove per ottenere il valore di key specificato.

1

Per tale manipolazione di array/raccolta in Javascript, suggerisco di utilizzare la libreria underscorejs. Fornisce funzioni che, per me, rendono tutto molto più semplice. Nel tuo caso:

function find_value(array, key) { 
    // find will run the provided function for every object in array 
    var obj_found = _.find(array, function(obj) { 
     // keys returns the keys inside an object 
     // so if the key of currently examined object 
     // is what we are looking for, return the obj 
     if (_.keys(obj)[0] === key) { 
      return obj; 
     } 
    }); 
    // if an object with such key was found return its value 
    if (obj_found) { 
     return obj_found[key]; 
    } else { 
     return null; 
    } 
} 

Here è un violino di lavoro di quello che sto suggerendo.

Problemi correlati