簡體   English   中英

從對象數組中,返回新數組中的鍵

[英]From an array of objects, return key in new array

我有一個對象數組,並且必須以新數組返回關鍵的puppies :此函數采用以下格式的狗數組:

[
  {breed: 'Labrador', puppies: ['Fluffy', 'Doggo', 'Floof'] },
  {breed: 'Rottweiler', puppies: ['Biscuits', 'Mary'] }
]

它應該返回所有狗的所有幼犬的數組:

['Fluffy', 'Doggo', 'Floof', 'Biscuits', 'Mary']

到目前為止,這是我的代碼:

function collectPuppies (dogs) {

    let solution=[];
    for(let i=0; i<dogs.length; i++){
      solution.push(dogs[i].puppies);
    }
    return solution;
  }

它將名稱添加到解決方案,但在[[ ]]之間返回它們:

Expected [ [ 'Spot', 'Spotless' ] ] to deeply equal [ 'Spot', 'Spotless' ]

我已經在線程中看到了我的解決方案,所以我相信我還不算太遠,但無法弄清楚我在做什么錯。 誰能幫我嗎? 提前致謝。

使用傳播語法將項目推入數組:

 const dogs = [{"breed":"Labrador","puppies":["Fluffy","Doggo","Floof"]},{"breed":"Rottweiler","puppies":["Biscuits","Mary"]}]; function collectPuppies(dogs) { const solution = []; for (let i = 0; i < dogs.length; i++) { solution.push(...dogs[i].puppies); } return solution; } console.log(collectPuppies(dogs)); 

另一個選擇是使用Array.map()獲得幼犬,並通過擴展到Array.concat()使結果變平:

 const dogs = [{"breed":"Labrador","puppies":["Fluffy","Doggo","Floof"]},{"breed":"Rottweiler","puppies":["Biscuits","Mary"]}]; const collectPuppies = (dogs) => [].concat(...dogs.map(({ puppies }) => puppies)); console.log(collectPuppies(dogs)); 

你可以抗拒。

 const dogs = [ {breed: 'Labrador', puppies: ['Fluffy', 'Doggo', 'Floof'] }, {breed: 'Rottweiler', puppies: ['Biscuits', 'Mary'] } ] const collectPuppies = dogs => dogs.map(d => d.puppies).reduce((a,b) => a.concat(b), []); console.log(collectPuppies(dogs)); 

您只需要reduce Array.prototype。

 x=[ {breed: 'Labrador', puppies: ['Fluffy', 'Doggo', 'Floof'] }, {breed: 'Rottweiler', puppies: ['Biscuits', 'Mary'] } ] ; var result=x.reduce((y,e)=>y.concat(e.puppies),[]); console.log(result); 

Array.prototype.push會將每個參數推入數組,但不會推入每個參數的單個數組元素。

更正代碼的最簡單方法是用concat替換push

concat()方法用於合並兩個或多個數組。

function collectPuppies(dogs) {
   let solution = [];
   for (let i=0; i < dogs.length; i++){
       solution = solution.concat(dogs[i].puppies);
   }
   return solution;
}

在對象數組中,小狗也是數組。 因此,您要將數組添加到數組中。 代替:

solution.push(dogs[i].puppies);

您需要遍歷puppies數組,並將每個pupple分別添加到解決方案數組。 第二個內部循環沒有將'puppies'字段添加到解決方案數組,而是循環遍歷每個對象的puppies數組並將其添加到solution數組。 通過在puppies數組上調用forEach()可以輕松完成第二個內部循環。 例如:

dogs[i].puppies.forEach((puppy) => {solution.push(puppy)});

那么最后一個函數是:

function collectPuppies (dogs) {
    let solution=[];
    for(let i=0; i<dogs.length; i++){
       dogs[i].puppies.forEach((puppy) => {solution.push(puppy)});
    }
    return solution;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM