gpt4 book ai didi

javascript - 从对象数组中,返回新数组中的键

转载 作者:行者123 更新时间:2023-11-30 07:52:34 24 4
gpt4 key购买 nike

我有一个对象数组,必须在新数组中返回键 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' ]

我在 this 中看到了我的解决方案线程,所以我相信我并不太远,但无法弄清楚我做错了什么。谁能帮我吗?提前致谢。

最佳答案

使用 spread syntax将项目插入数组:

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));

关于javascript - 从对象数组中,返回新数组中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49497904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com