我在下面有一個陣列。對于"_id"此陣列中的每個物件元素中的每一個,都有一個名為 的陣列"form"。
我想得到的是answerValuefor each _id,其中的field值form是cState。
let array = [{
"_id" : "a1",
"user" : "John",
"form" : [
{
"question" : "question1",
"questionValue" : "Which state do you live in?",
"answers" : [
"answer1"
],
"answerValue" : [
"Arizona"
],
"field" : "cState",
},
{
"question" : "question2",
"questionValue" : "What is your nationality?",
"answers" : [
"answer2"
],
"answerValue" : [
"American"
],
"field" : "nationality",
},
"_id" : "a2",
"user" : "Mike",
"form" : [
{
"question" : "question1",
"questionValue" : "Which state do you live in?",
"answers" : [
"answer3"
],
"answerValue" : [
"Florida"
],
"field" : "cState",
},
{
"question" : "question2",
"questionValue" : "What is your nationality?",
"answers" : [
"answer2"
],
"answerValue" : [
"American"
],
"field" : "nationality",
},
}]
預期產出
[{
"_id" : "a1",
"user" : "John",
"answerValue": "Arizona"
},
{
"_id" : "a2",
"user" : "Mike",
"answerValue": "Florida"
},
]
這是我嘗試過的:
let allDemographics
allDemographics = array.map((item) => {
return {
user: item.array._id,
nationality: item.array.nationality,
state: item.array.form,
}
})
uj5u.com熱心網友回復:
試試看 :
let array = [
{
"_id" : "a1",
"user" : "John",
"form" : [
{
"question" : "question1",
"questionValue" : "Which state do you live in?",
"answers" : [
"answer1"
],
"answerValue" : [
"Arizona"
],
"field" : "cState",
},
{
"question" : "question2",
"questionValue" : "What is your nationality?",
"answers" : [
"answer2"
],
"answerValue" : [
"American"
],
"field" : "nationality",
}
]
},
{
"_id" : "a2",
"user" : "Mike",
"form" : [
{
"question" : "question1",
"questionValue" : "Which state do you live in?",
"answers" : [
"answer3"
],
"answerValue" : [
"Florida"
],
"field" : "cState",
},
{
"question" : "question2",
"questionValue" : "What is your nationality?",
"answers" : [
"answer2"
],
"answerValue" : [
"American"
],
"field" : "nationality",
},
]
}
]
let allDemographics = array.map((item) => {
let fieldCstate = item.form.find(form => form.field === "cState")
return {
_id: item._id,
user: item.user,
answerValue: fieldCstate.answerValue[0],
}
})
console.log(allDemographics)
uj5u.com熱心網友回復:
我喜歡這個,因為您在映射之前進行過濾。如果你有一個大陣列,這可能會給你更好的性能:
let arr = array.filter(x => x.form.every(y => y.field === "cState"));
const data = arr.map((x) => ({ user: x.user, id: x._id,
answer:x.form[0].answerValue }));
console.log(data[0].answer)
或者一個班輪:
let arr = array.filter(x => x.form.every(y => y.field === "cState"))
.map(x => ({ user: x.user, id: x._id, answer:x.form[0].answerValue })
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/481216.html
標籤:javascript 数组
