简体   繁体   English

JavaScript-按键搜索对象属性并将其值添加到数组

[英]JavaScript - Search object property by key and add its value to array

Let's say I have an object like this: 假设我有一个这样的对象:

var object =  {
  "Defender": {
    "player-1868": {
      "birthdate": "1 July 1996",
      "club_country": "IQ",
      "club_id": 171,
      "club_name": "Erbil",
      "forename": "Burhan Jumaah",
      "id": 1868,
      "league_id": 12,
      "league_name": "Iraqi Premier League",
      "name": "Burhan Jumaah",
      "nationality": "iq",
      "nationality_full": "Iraq",
      "position": "Defender",
      "surname": "Razzaq",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  },
  "Goalkeeper": {
    "player-3076": {
      "birthdate": "15 December 1985",
      "club_country": "QA",
      "club_id": 1,
      "club_name": "Lekhwiya",
      "comments": [
        {
          "comment": "xxx",
          "name": "guy tester",
          "photoURL": "http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg",
          "time": 1496529030321,
          "user": "y884F42mLCVdld5V5cMeRpl11gJ2"
        }
      ],
      "forename": "Qasem Abdulhamed",
      "id": 3076,
      "league_id": 1,
      "league_name": "Qatar Stars League",
      "name": "Qasem Burhan",
      "nationality": "qa",
      "nationality_full": "Qatar",
      "position": "Goalkeeper",
      "surname": "Burhan",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    },
    "player-3532": {
      "birthdate": "2 April 1992",
      "club_country": "SA",
      "club_id": 18,
      "club_name": "Al Ittihad",
      "forename": "Fawaz",
      "id": 3532,
      "league_id": 2,
      "league_name": "Saudi Professional League",
      "name": "Fawaz Al Qarni",
      "nationality": "sa",
      "nationality_full": "Saudi Arabia",
      "position": "Goalkeeper",
      "surname": "Al Qarni",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  }
};

How would I, using lodash , traverse through this object and add every time the property id appears inside an object key of player-xxxxxx , add that value to an array. 我将如何使用lodash遍历此对象,并在每次属性id出现在player-xxxxxx的对象键中时添加该值,然后将该值添加到数组中。 Essentially, getting all of the player IDs in a single array ? 本质上,是否将所有玩家ID放在一个array

You can Array#reduce recursively on the object's keys to find the search string (player-), and create and extract the values: 您可以对对象的键递归Array#reduce以找到搜索字符串(player-),并创建和提取值:

 var object = {"Defender":{"player-1868":{"birthdate":"1 July 1996","club_country":"IQ","club_id":171,"club_name":"Erbil","forename":"Burhan Jumaah","id":1868,"league_id":12,"league_name":"Iraqi Premier League","name":"Burhan Jumaah","nationality":"iq","nationality_full":"Iraq","position":"Defender","surname":"Razzaq","votes":["y884F42mLCVdld5V5cMeRpl11gJ2"]}},"Goalkeeper":{"player-3076":{"birthdate":"15 December 1985","club_country":"QA","club_id":1,"club_name":"Lekhwiya","comments":[{"comment":"xxx","name":"guy tester","photoURL":"http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg","time":1496529030321,"user":"y884F42mLCVdld5V5cMeRpl11gJ2"}],"forename":"Qasem Abdulhamed","id":3076,"league_id":1,"league_name":"Qatar Stars League","name":"Qasem Burhan","nationality":"qa","nationality_full":"Qatar","position":"Goalkeeper","surname":"Burhan","votes":["y884F42mLCVdld5V5cMeRpl11gJ2"]},"player-3532":{"birthdate":"2 April 1992","club_country":"SA","club_id":18,"club_name":"Al Ittihad","forename":"Fawaz","id":3532,"league_id":2,"league_name":"Saudi Professional League","name":"Fawaz Al Qarni","nationality":"sa","nationality_full":"Saudi Arabia","position":"Goalkeeper","surname":"Al Qarni","votes":["y884F42mLCVdld5V5cMeRpl11gJ2"]}}}; function searchProps(searchStr, object) { return Object.keys(object).reduce(function(arr, key) { // reduce the objects keys to an array key.indexOf(searchStr) === -1 || arr.push(key.slice(searchStr.length)); // if a key contains the search string, take whatever after it var propValue = object[key]; if(typeof propValue === 'object' && propValue !== null) { // if the value of the property is an array, run it through search props return arr.concat(searchProps(searchStr, propValue)); } return arr; }, []); } var result = searchProps('player-', object); console.log(result); 

With Javascript, to traverse the keys and get each id, you may use "for" like below sample code: 使用Javascript来遍历键并获取每个ID,您可以像下面的示例代码一样使用“ for”:

var obj =  {
  "Defender": {
    "player-1868": {
      "birthdate": "1 July 1996",
      "club_country": "IQ",
      "club_id": 171,
      "club_name": "Erbil",
      "forename": "Burhan Jumaah",
      "id": 1868,
      "league_id": 12,
      "league_name": "Iraqi Premier League",
      "name": "Burhan Jumaah",
      "nationality": "iq",
      "nationality_full": "Iraq",
      "position": "Defender",
      "surname": "Razzaq",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  },
  "Goalkeeper": {
    "player-3076": {
      "birthdate": "15 December 1985",
      "club_country": "QA",
      "club_id": 1,
      "club_name": "Lekhwiya",
      "comments": [
        {
          "comment": "xxx",
          "name": "guy tester",
          "photoURL": "http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg",
          "time": 1496529030321,
          "user": "y884F42mLCVdld5V5cMeRpl11gJ2"
        }
      ],
      "forename": "Qasem Abdulhamed",
      "id": 3076,
      "league_id": 1,
      "league_name": "Qatar Stars League",
      "name": "Qasem Burhan",
      "nationality": "qa",
      "nationality_full": "Qatar",
      "position": "Goalkeeper",
      "surname": "Burhan",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    },
    "player-3532": {
      "birthdate": "2 April 1992",
      "club_country": "SA",
      "club_id": 18,
      "club_name": "Al Ittihad",
      "forename": "Fawaz",
      "id": 3532,
      "league_id": 2,
      "league_name": "Saudi Professional League",
      "name": "Fawaz Al Qarni",
      "nationality": "sa",
      "nationality_full": "Saudi Arabia",
      "position": "Goalkeeper",
      "surname": "Al Qarni",
      "votes": [
        "y884F42mLCVdld5V5cMeRpl11gJ2"
      ]
    }
  }
};

var arr = [];
tgtObj = obj["Defender"];
for(var key in tgtObj){
    if (tgtObj.hasOwnProperty(key)){
    console.log(key);
    arr.push(tgtObj[key]["id"]);
  }
}
tgtObj = obj["Goalkeeper"];
for(var key in tgtObj){
    if (tgtObj.hasOwnProperty(key)){
    console.log(key);
    arr.push(tgtObj[key]["id"]);
  }
}
console.log(arr);

Iterate through the object keys check to see if the string starts with "player-" and then push into an empty array the last four characters. 遍历对象键以检查字符串是否以“ player-”开头,然后将最后四个字符压入一个空数组。

 var object = { "Defender": { "player-1868": { "birthdate": "1 July 1996", "club_country": "IQ", "club_id": 171, "club_name": "Erbil", "forename": "Burhan Jumaah", "id": 1868, "league_id": 12, "league_name": "Iraqi Premier League", "name": "Burhan Jumaah", "nationality": "iq", "nationality_full": "Iraq", "position": "Defender", "surname": "Razzaq", "votes": [ "y884F42mLCVdld5V5cMeRpl11gJ2" ] } }, "Goalkeeper": { "player-3076": { "birthdate": "15 December 1985", "club_country": "QA", "club_id": 1, "club_name": "Lekhwiya", "comments": [{ "comment": "xxx", "name": "guy tester", "photoURL": "http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg", "time": 1496529030321, "user": "y884F42mLCVdld5V5cMeRpl11gJ2" }], "forename": "Qasem Abdulhamed", "id": 3076, "league_id": 1, "league_name": "Qatar Stars League", "name": "Qasem Burhan", "nationality": "qa", "nationality_full": "Qatar", "position": "Goalkeeper", "surname": "Burhan", "votes": [ "y884F42mLCVdld5V5cMeRpl11gJ2" ] }, "player-3532": { "birthdate": "2 April 1992", "club_country": "SA", "club_id": 18, "club_name": "Al Ittihad", "forename": "Fawaz", "id": 3532, "league_id": 2, "league_name": "Saudi Professional League", "name": "Fawaz Al Qarni", "nationality": "sa", "nationality_full": "Saudi Arabia", "position": "Goalkeeper", "surname": "Al Qarni", "votes": [ "y884F42mLCVdld5V5cMeRpl11gJ2" ] } } }; function getPlayers(object) { let items = []; for (let i in object) { let key = Object.keys(object[i]); key.forEach(i => i.startsWith('player') ? items.push(i.substring(i.length -4)) : ''); } return items; } console.log(getPlayers(object)); 

I was able to solve it myself after some more time on it. 经过一些时间,我自己能够解决它。

 var obj = { Defender: { "player-1868": { club_id: 171, id: 1868, league_id: 12, name: "Burhan Jumaah" } }, Goalkeeper: { "player-3076": { club_id: 1, id: 3076, league_id: 1, name: "Qasem Burhan" }, "player-3532": { club_id: 18, id: 3532, league_id: 2, name: "Fawaz Al Qarni" } } }; function searchForProp(lookingFor, obj, arrYielded) { var arr = arrYielded ? arrYielded : []; Object.keys(obj).forEach(function(key, idx) { if (typeof(obj[key]) === 'object') { searchForProp(lookingFor, obj[key], arr); } else { if (key === 'id') { arr.push(obj[key]); } } }); return arr; } var allIDs = searchForProp('id', obj); console.log(allIDs); 

The simplest way that I could think of using lodash: 我可以想到的使用lodash的最简单方法是:

_(object).map(_.keys).flatten().value();

This of course assumes that the player keys are always at the same level in the object hierarchy. 当然,这假定玩家键在对象层次结构中始终处于同一级别。

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

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