gpt4 book ai didi

Javascript 嵌套 .map() 返回多个数组

转载 作者:行者123 更新时间:2023-11-30 09:20:55 25 4
gpt4 key购买 nike

假设我有一个像这样的 JSON 结构:

{
"firstData": [{
"secondData": [{
"thirdData": [{
"value": "whatever"
}]
}]
}]
}

我需要从 thirdData value === "whatever" 进行映射

所以我在做

 const result = firstData.map(first => {
return first.secondData.map(second => {
return second.thirdData.map(third => {
return third.value === 'whatever';
});
});
});

这工作得很好,但结果是另一个深度嵌套的数组(如 [ [ [ {results..} ] ] ])。我知道我可以通过其他方式将其展平为单个数组,但我觉得我很想念 .map()。如何将此结果修改为包含 thirdData 值的单个数组,其中值是我想要的值?

所需的结果是单个 thirdData 对象数组:

[{ value: 'whatever'}, ... {n}]

最佳答案

您可以使用 Array#reduce用于减少为单个值(在本例中为单个数组)和 Array#forEach 用于迭代嵌套数组。

const data = {
"firstData": [{
"secondData": [{
"thirdData": [{
"value": "whatever"
}]
}]
}]
}

const result = data.firstData.reduce((arr, first) => {
// iterate over the second level array
first.secondData.forEach(second => {
// iterate over the third level array
second.thirdData.forEach(third => {

// push the value into the result array,
// change here, in case you want the value
//arr.push(third.value === 'whatever');

// in case you need the object then do it like
if(third.value === 'whatever') arr.push(third);

});
});
// return the array reference for the next iteration
return arr;

// set the initial value as an array for the result
}, []);

console.log(result);

关于Javascript 嵌套 .map() 返回多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51743372/

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