gpt4 book ai didi

javascript - 使用map函数根据条件返回一个数组对象而不是所有对象

转载 作者:行者123 更新时间:2023-11-28 12:12:46 25 4
gpt4 key购买 nike

我想根据ReactJS中的条件使用map函数从数组中获取一个索引值。

目前,如果条件通过,我将获取所有索引值,但我想在条件为真时停止条件。这样我在返回时就会有​​一个索引...

JSON 对象:

question: [

{
'question_type': 'TEXT',
'question': 'how long have the founders known each other?',
'question_status': 'Done',
'expectedAnswer': "",
'answer': '5 yrs'
},
{
'question_type': 'EITHER',
'question': 'does any founder have an exit?',
'question_status': 'Pending',
'expectedAnswer':['Yes','No'],
'answer': "",
},
{
'question_type': 'DROPDOWN',
'question': 'Where are you from?',
'question_status': 'Pending',
'expectedAnswer':['india','USA','UK'],
'answer': "",
},
]

正在执行过滤器的 React 函数

const currentQuestion = question.map(function (data, i) {
if (data.question_status === 'Pending') {
return (
<Row key={i} className='chat-box'>
<Col xl='1' lg='1' md='1' className="question-image">
<img src='images/chatbot/rectangle-26.png' />
</Col>
<Col xl='11' lg='11' md='11' className="question-text">
{data.question}
</Col>

<Col xl="11" lg="11" md="11" className="answer-box ">
{/* <img className="answer-image pull-right" src='images/chatbot/group-9.png' /> */}
<div className="pull-right custome-radio">
{data.question_type === 'EITHER'? this.renderEitherField(data.expectedAnswer):null}
</div>
</Col>
</Row>
);
}

}.bind(this));

预期输出:

{
'question_type': 'EITHER',
'question': 'does any founder have an exit?',
'question_status': 'Pending',
'expectedAnswer':['Yes','No'],
'answer': "",

}

我想单独过滤第一个索引值,而不是第一个和第二个。目前我正在获取第一个和第二个索引值,因为 Question_status 都是“待处理”,但在这里我只想获取第一个索引值(一旦第一次发生,它必须停止返回值)

如果这不是最好的方法,请告诉我......

最佳答案

您可以使用Array.find方法。它返回数组中满足条件的第一个值,否则未定义。

const data = [

{
'question_type': 'TEXT',
'question': 'how long have the founders known each other?',
'question_status': 'Done',
'expectedAnswer': "",
'answer': '5 yrs'
},
{
'question_type': 'EITHER',
'question': 'does any founder have an exit?',
'question_status': 'Pending',
'expectedAnswer':['Yes','No'],
'answer': "",
},
{
'question_type': 'DROPDOWN',
'question': 'Where are you from?',
'question_status': 'Pending',
'expectedAnswer':['india','USA','UK'],
'answer': "",
},
]
const out = data.find(x => x.question_status === 'Pending')

console.log(out)

Please keep in mind that Array.find is not supported on IE. You need to use a Polyfill.

The other approach can be to return 0th index of the filtered array. If present it will return the value else undefined.

关于javascript - 使用map函数根据条件返回一个数组对象而不是所有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57475867/

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