简体   繁体   中英

Access JSON object key/value where value is an array using underscorejs

I have a local JSON dataset (outlined below) and am trying to use the _.where method to retrieve specific values from within the dataset.

JSON File

"data": [{
    "singles_ranking": [116],
    "matches_lost": ["90"],
    "singles_high_rank": [79],
    "matches_won": ["170"],
    "singles_ranking/_source": ["116"],
    "year_matches_won": ["11"],
    "name": ["Pfizenmaier Dinah"],
    "gender": ["woman"],
    "_resultNumber": 1,
  },{etc},{etc}];

Currently I am trying to retrieve values from within the dataset like so:

var mappedPlayers = _.map(players,function(key,val){return key});
var filteredPlayers = _.where(mappedPlayers, {name:'Pfizenmaier Dinah'}); 
console.log(filteredPlayers);

This currently returns undefined . I am 90% sure that this is because the key values are stored within an array however, I am not sure how I can modify this _.where condition to actually make it return the text within the value attribute.

Any help would be greatly welcomed. Thank you for reading!

With ._where it is not possible, but you can use _.filter , like so

var where = {key: 'name', value: 'Pfizenmaier Dinah'};
var filteredPlayers = _.filter(players, function (el) {
    // check if key exists in Object, check is value is Array, check if  where.value exists  in Array  
    return el[where.key] && _.isArray(el[where.key]) && _.indexOf(el[where.key], where.value) >= 0;
});

Example

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