我正在寻找一种增加数字的方法,因此我需要先找到一个由ID标识的对象。更具体地说,我想增加特定对象的票数。
数据结构如下:
const polls = [
{
id: "9efd91dc-b762-11e8-bfb8-c471feb11e42",
owner: "d926e95c-b696-11e8-8a0f-c471feb11e42",
question: "How are you? 1536849484",
tenement: "0cec2fc2-b697-11e8-8a0f-c471feb11e42",
participation: 0,
poll_answer_options: [
{
id: "9efd9b32-b762-11e8-bfb8-c471feb11e42",
owner: "d926e95c-b696-11e8-8a0f-c471feb11e42",
answer_text: "Not so Fine",
votes: 0
},
{
id: "9efd97b8-b762-11e8-bfb8-c471feb11e42",
owner: "d926e95c-b696-11e8-8a0f-c471feb11e42",
answer_text: "Fine",
votes: 0 // -> want to increment
}
]
},
{
id: "13b43584-b697-11e8-b2c2-c471feb11e42",
owner: "d926e95c-b696-11e8-8a0f-c471feb11e42",
question: "How are you? 1536762062",
tenement: "0cec2fc2-b697-11e8-8a0f-c471feb11e42",
participation: 1,
poll_answer_options: [
{
id: "13b43f66-b697-11e8-b2c2-c471feb11e42",
owner: "d926e95c-b696-11e8-8a0f-c471feb11e42",
answer_text: "Not so Fine",
votes: 1
},
{
id: "13b43bd8-b697-11e8-b2c2-c471feb11e42",
owner: "d926e95c-b696-11e8-8a0f-c471feb11e42",
answer_text: "Fine",
votes: 0
}
]
}
];
我尝试使用如下所示的JavaScript find方法,但这不起作用。
let pollAnswerOptions = polls.find(
poll => poll.poll_answer_options.id === "9efd97b8-b762-11e8-bfb8-c471feb11e42"
);
答案 0 :(得分:1)
您需要一种嵌套方法,如果只有一个id
可以找到,则可以使用短路来防止更多的迭代。
const
polls = [{ id: "9efd91dc-b762-11e8-bfb8-c471feb11e42", owner: "d926e95c-b696-11e8-8a0f-c471feb11e42", question: "How are you? 1536849484", tenement: "0cec2fc2-b697-11e8-8a0f-c471feb11e42", participation: 0, poll_answer_options: [{ id: "9efd9b32-b762-11e8-bfb8-c471feb11e42", owner: "d926e95c-b696-11e8-8a0f-c471feb11e42", answer_text: "Not so Fine", votes: 0 }, { id: "9efd97b8-b762-11e8-bfb8-c471feb11e42", owner: "d926e95c-b696-11e8-8a0f-c471feb11e42", answer_text: "Fine", votes: 0 }] }, { id: "13b43584-b697-11e8-b2c2-c471feb11e42", owner: "d926e95c-b696-11e8-8a0f-c471feb11e42", question: "How are you? 1536762062", tenement: "0cec2fc2-b697-11e8-8a0f-c471feb11e42", participation: 1, poll_answer_options: [{ id: "13b43f66-b697-11e8-b2c2-c471feb11e42", owner: "d926e95c-b696-11e8-8a0f-c471feb11e42", answer_text: "Not so Fine", votes: 1 }, { id: "13b43bd8-b697-11e8-b2c2-c471feb11e42", owner: "d926e95c-b696-11e8-8a0f-c471feb11e42", answer_text: "Fine", votes: 0 }] }],
id = '9efd97b8-b762-11e8-bfb8-c471feb11e42';
polls.some(o => o.poll_answer_options.some(option => {
if (option.id === id) {
++option.votes;
return true;
}
}));
console.log(polls);
.as-console-wrapper { max-height: 100% !important; top: 0; }