I am getting setting data from the single object which includes, string, number and array.
{
"settings_1": "yes",
"settings_2": 5,
"settings_3": "no",
"settings_4": true,
"settings_5": true,
"settings_6": [],
}
I am just trying to convert "yes" or "no" values into true/false so I can render my antd components.
I tried the following way but had an issue.
return await axios.get("http://localhost.test/wp-json/v1/settings/")
.then(response => {
return Object.fromEntries(Object.entries(response.data).map(([k, v]) => {
if ( v === 'yes' ) {
v = true
} else if ( v === 'no' ) {
v = false
}
[k, v]
}))
})
.then(res => {
console.log('res data:', res);
}
CodePudding user response:
Just replace values of the keys you iterate using for (key in obj)
.
var response = {
data: {
"settings_1": "yes",
"settings_2": 5,
"settings_3": "no",
"settings_4": true,
"settings_5": true,
"settings_6": [],
}
};
for (var k in response.data) {
v = response.data[k];
if (v === 'yes') {
v = true
}
if (v === 'no') {
v = false
}
response.data[k] = v;
}
console.log(response.data);
CodePudding user response:
You could do it like:
let arr = {
"settings_1": "yes",
"settings_2": 5,
"settings_3": "no",
"settings_4": true,
"settings_5": true,
"settings_6": [],
}
let arr = Object.keys(arr).map((key) => {
if (typeof arr[key as keyof typeof arr] === 'string') return {[key]: arr[key as keyof typeof arr] === 'yes'};
else return {[key]: arr[key as keyof typeof arr]};
})
console.log(arr);