0

I would like to create a nested object like below base on input forms. First key would be the name attribute, inside it would get required: true if the onput contains reqiuder attribute etc. I assume I need a nested foreach for that, I'm not sure. I added the code what I tried so far.

This is the object I like to create:

var obj = {
    'email.address': {
        required: true,
        email: true
     },
     'first.name': {
         required: false
     },
     'last.name': {
         required: true
     }
};

This is the code I have at the moment:

var formInputs = $('input'),
    obj = {};

$.each(formInputs, function(key, value) {
  obj[this.name] = value.name;
});

console.log(obj)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input type="email" name="email.address" placeholder="Email address" required />
  <input type="text" name="first.name" placeholder="First name" />
  <input type="text" name="last.name" placeholder="Last name" required />
</form>

2
  • It's not a great idea to include . in a property name since . is the natural syntax for separating an object from its properties/methods. The general convention for multiple word names is to use Pascal Case as in: firstName, lastName, emailAddress. Commented Feb 23, 2021 at 23:12
  • I know that, but these inputs are generated by a system and I can't do anything about it. Commented Feb 23, 2021 at 23:15

2 Answers 2

1

The issue is that you aren't waiting for your document to load before parsing.

jquery lets you wait until the document is ready with $(document).ready()

here is an example you can replace your js with

$(document).ready(function(){
var formInputs = $('input'),
    obj = {};
    $.each(formInputs, function(key, value) {
        obj[this.name] = {required: value.required}
    });
    console.log(obj)
})
Sign up to request clarification or add additional context in comments.

Comments

1
for (var i = 0, v; v = formInputs[i]; i++) { 
    for (var o of Object.keys(obj)) { 
        if (o !== v.name) { 
            continue;
        }
        for (var n of Object.keys(obj[o])) {
            v[n] = obj[o][n];
        }
    }
}

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.