Reputation: 719
I'm looking for a way of incrementing a number, therefore I need to find the object which is identified by an id first. More specifically, I want to increment the votes of a specific object.
The data structure looks like this:
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
}
]
}
];
I tried with the JavaScript find method like shown below, but this doesn't work.
let pollAnswerOptions = polls.find(
poll => poll.poll_answer_options.id === "9efd97b8-b762-11e8-bfb8-c471feb11e42"
);
Upvotes: 0
Views: 91
Reputation: 386848
You need a nested approach and if you have only one id
to find, you could use a short circuit to prevent more iterating.
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; }
Upvotes: 1