Below the given object i need to reset the value for the key "label", "value", "ward" and "tole" to empty(' ') using javascript.
state ={
"label": "लुम्बिनी प्रदेश",
"value": 21,
"province": {
"label": "लुम्बिनी प्रदेश",
"value": "23"
},
"district": {
"label": "अर्घाखाँची",
"value": "20"
},
"local_level": {
"label": "भूमिकास्थान नगरपालिका",
"value": "17"
},
"ward": "10",
"tole": "venas"
}
I have tried to get the keys of the object
Object.keys(state).map(item=>({key: item}))
but don't have idea how to reset the value of the object.
The final result should look like this. the state object may evolve i.e the key and value of the object may be added or may be removed.
state ={
"label": '',
"value": '',
"province": {
"label": '',
"value": ''
},
"district": {
"label": '',
"value": ''
},
"local_level": {
"label": '',
"value": ''
},
"ward": '',
"tole": ''
}
You can iterate through the object using the for...in Loop in JS. And then, if you find those keys, then just replace their values with an empty string. And since, you also want to check again, that if the value of the keys are objects, and if they are, then you can again loop through them, and change their value to an empty string.
for (let key in state) {
if (typeof state[key] === 'object') {
// if the value of the key is an object, then we will again loop through the value of that key, and change the value of those keys to an empty string.
for (let nestedKey in state[key]) {
// console.log(nestedKey, state[key][nestedKey]);
if (
nestedKey === "label" ||
nestedKey === "value" ||
nestedKey === "ward" ||
nestedKey === "tole"
) {
state[key][nestedKey] = " ";
}
}
}
if (key === "label" || key === "value" || key === "ward" || key === "tole") {
state[key] = " ";
}
}
This code will work, and will change all those values to empty string.
let setToDefault = state => Object.assign(state, { label: '', value: '', ward: '', tole: '' });