0

I have a multiple step form. To validate each step I thought it might be handy to create a JSON object, Where each key acts as a step with the right fields.

My object is not finished, but looks now like this:

let validationSteps = {
0: {
    location: null,
    duration: null,
    membershipType: null,
},
1: {
    fname: null,
}

};

I want to fill each item by using an event listener. For example, when you fill in your first name. It should trigger something that searches for fname in the object, and fills it. But I have no clue how to find the key, since it's already inside an object.

1 Answer 1

1

According to this data structure. You should use Object.keys() to do a for loop to find where is the key you are looking for.(It looks like an array but you use it like a json)

function setValue(json,key,value){
    // for loop to check all the keys
    for(let i = 0; i < Object.keys(json).length; i++){
        let keys = Object.keys(json);
        let obj = json[keys[i]];
        
        // if this obj has the key
        if(Object.keys(obj).includes(key)){
            obj[key] = value;
        }
    }
    return json;
}

// example
setValue(validationSteps ,"fname","this is name");

Result will looks like:

{
    "0": {
        "location": null,
        "duration": null,
        "membershipType": null
    },
    "1": {
        "fname": "this is name"
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for your answer. I found out about this solution similar to yours, before I read your answer. Here's my code pastebin.com/H4A6r8FS Could you take a look at it, to see if it's fine, or that it needs improvement? Furthermore it works exactly like your code!
I also added that setValue method within my form input event listener. So that it gets triggered on the input you're filling in.
It look shorter than my old ones, but there has one thing you need to check. for(key in Object.keys(validationSteps)) this loop will get not only your object items but also get the properties. For example, if you or someone add property to Object. It may cause some error.You can run the code below and you will see the result in console.
Object.prototype.a = "custom prototype"; for(key in Object.keys(validationSteps)){ console.log(key); }
Ah okay, I like your way. Btw in my example you saw some pre-defined values. I did that because those radios are always checked when the page load. Is that a correct way of doing that? Cause they'll only change when input listener has been triggered
|

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.