Sebastiaan
Sebastiaan

Reputation: 116

How to assign object values from an array in Javascript

I've made a constructor for an object called "Book". I've captured all the values from a form in an array. Now I want to assign the values of this array to this constructor. However, I'm quite stuck because I don't seem to find what I'm looking for on Google or StackOverflow.

Here's my code:

let formArray = [];
document.querySelectorAll('input[type="text"]').forEach(function (node) {
    formArray.push(node.value);
});

let newBook = new Book();
let idx = 0;
Object.keys(newBook).forEach(function (k) {
    k = formArray[idx];
})

However, this is my log:

Book {title: undefined, author: undefined, nPages: undefined, isRead: undefined}
title: undefined
author: undefined
nPages: undefined
isRead: undefined

Please help me figure this out!

Upvotes: 1

Views: 55

Answers (2)

thedude
thedude

Reputation: 9814

This is how you can setup something like what you are after, I've including just two properties for simplicity.

class Book {
  constructor({ title, author }) {
    this.title = title
    this.author = author
  }
}

const values = {}
document.querySelectorAll('input[type="text"]').forEach(function (node) {
    values[node.name] = node.value
});

console.log(new Book(values))
<input type="text" name="title" value="The Never Ending Story" />
<input type="text" name="author" value="Michael Ende" />

Upvotes: 2

arslan
arslan

Reputation: 1144

let formArray = [];
document.querySelectorAll('input[type="text"]').forEach(function (node) {
    formArray.push(node&&node.value);
});

let newBook = new Book();
let idx = 0;
Object.keys(newBook).forEach(function (k) {
    k = formArray[idx];
})

try this one i think js running code before node.value

Upvotes: 0

Related Questions