1

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!

3
  • are you sure you are getting node.value? Commented May 3, 2020 at 8:07
  • Yeah formArray.push(node.value) works as expected, console.log(formArray) returns: ["1", "1", "1", "1"] (for example). Commented May 3, 2020 at 8:35
  • yes because its working late i answred this below Commented May 3, 2020 at 10:34

2 Answers 2

2

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" />

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.