Reputation: 541
This is what I have so far:
var onepage = [{
name: 'Custom Design',
hours: 5
},{
name: 'Premium Theme',
hours: 2
},{
name: 'SEO',
hours: 5
},{
name: 'Backlink Building',
hours: 6
},{
name: 'Article Writing',
hours: 7
},{
name: 'Copywriting',
hours: 3
},{
name: 'Development',
hours: 8
}
]
window.onkeyup = keyup;
var numberofPages;
function keyup(e) {
numberofPages = e.target.value;
newHours = [];
for (var i = 0; i < onepage.length; i++) {
var totalHours = numberofPages * onepage[i].hours;
newHours.push(totalHours);
}
console.log(newHours);
}
<input type="text" placeholder="Number of Pages" id="pages" value="1">
The user inputs # of pages and the it gets multiplied by hours
and pushed into the array newHours
and from there I want to update the original object array hours.
I'm not sure how to update
it, or does it make sense to create a new array of objects?
Upvotes: 0
Views: 2865
Reputation: 28445
You can update the array directly without creating a newArray. Please note, that updating directly hours
of the original array will lead to undesired results. Hence, added a new property calculatedHours
var onepage = [{name: 'Custom Design',hours: 5},{name: 'Premium Theme',hours: 2},{name: 'SEO',hours: 5},{name: 'Backlink Building',hours: 6},{name: 'Article Writing',hours: 7},{name: 'Copywriting',hours: 3},{name: 'Development',hours: 8}];
window.onkeyup = keyup;
var numberofPages;
function keyup(e) {
numberofPages = e.target.value;
newHours = [];
for (var i = 0; i < onepage.length; i++) {
onepage[i].calculatedHours = numberofPages * onepage[i].hours;
}
console.log(onepage);
}
<input type="text" placeholder="Number of Pages" id="pages" value="1">
Upvotes: 1
Reputation: 73221
Just do a simple forEach loop like shown below. I've created it so that it gets updated once the user presses the enter key (13) inside the input. I'd suggest to put the listener on the input, not on the window in real code.
document.getElementById('foo').addEventListener('keyup', e => {
if (e.keyCode !== 13) return;
onepage.forEach(el => el.computed = el.hours * e.target.value);
console.log(onepage);
})
<input id="foo">
<script>
var onepage = [
{
name: 'Custom Design',
hours: 5
},
{
name: 'Premium Theme',
hours: 2
},
{
name: 'SEO',
hours: 5
},
{
name: 'Backlink Building',
hours: 6
},
{
name: 'Article Writing',
hours: 7
},
{
name: 'Copywriting',
hours: 3
},
{
name: 'Development',
hours: 8
}
]
</script>
Upvotes: 0