Home > front end >  Finding a key in a JSON object and giving it a value. (Javascript)
Finding a key in a JSON object and giving it a value. (Javascript)

Time:10-18

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.

CodePudding user response:

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"
    }
}
  • Related