gpt4 book ai didi

javascript - 将对象的属性访问到嵌套数组中 - Javascript

转载 作者:行者123 更新时间:2023-11-30 23:57:13 25 4
gpt4 key购买 nike

我想从以下数组中检索所有文本(文本 1,文本 2....):

[
{
"reviews":
[
{
"_id": "5e84239d6e24358b50f3fe4e",
"text": "My text 1"
},
{
"_id": "5e8423a46e24358b50f3fe4f",
"text": "My text 2"
}
]
},
{
"reviews":
[
{
"_id": "5e84239d6e24358b50f3fe4e",
"text": "My text 3"
},
{
"_id": "5e8423a46e24358b50f3fe4f",
"text": "My text 4"
}
]
},
{
"reviews":
[
{
"_id": "5e84239d6e24358b50f3fe4e",
"text": "My text 5"
},
{
"_id": "5e8423a46e24358b50f3fe4f",
"text": "My text 6"
}
]
}
]

该数组存储在名为stores 的变量中。

我尝试过以下方法:

const listText =stores.map(count => count.reviews.text//[null, null, null]
const listText =stores.map((count, i) => count.reviews[i].text)//无法读取未定义的属性“text”
const listText =stores.forEach((key, i) => key.reviews[i].text)//无法读取未定义的属性“text”

你能帮我一下吗?非常感谢

最佳答案

您不能使用 count.reviews.text 因为reviews是一个数组,所以您还应该迭代reviews:

const data = [
{
"reviews":
[
{
"_id": "5e84239d6e24358b50f3fe4e",
"text": "My text 1"
},
{
"_id": "5e8423a46e24358b50f3fe4f",
"text": "My text 2"
}
]
},
{
"reviews":
[
{
"_id": "5e84239d6e24358b50f3fe4e",
"text": "My text 3"
},
{
"_id": "5e8423a46e24358b50f3fe4f",
"text": "My text 4"
}
]
},
{
"reviews":
[
{
"_id": "5e84239d6e24358b50f3fe4e",
"text": "My text 5"
},
{
"_id": "5e8423a46e24358b50f3fe4f",
"text": "My text 6"
}
]
}
]

const listText = data.reduce((acc,current) => acc.concat(current.reviews.map(it => it.text)), [])

console.log(listText)

关于javascript - 将对象的属性访问到嵌套数组中 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60972052/

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