I am trying to change all values that may be turned into a number but come as a string
const array = [{
label: 'foo',
page: 1,
rank: '1',
decimal: '0.1'
},{
label: 'foo',
page: 1,
rank: '2',
decimal: '0.4'
}]
I would like to use this condition for all the values:
const returnValue = !isNaN(parseFloat(val)) ? parseFloat(val) : val
But not really sure how to iterate over the array of object without specifying each key
.
I have done this, but not sure how efficient it is
const res = json.map(obj => {
for (const [key, value] of Object.entries(obj)) {
obj[key] = !isNaN(parseFloat(value)) ? parseFloat(value) : value
}
return obj
})
console.log(res)
Desired output
const array = [{
label: 'foo',
page: 1,
rank: 1, // <-- Number
decimal: 0.1 // <-- Number
},{
label: 'foo',
page: 1,
rank: 2, // <-- Number
decimal: 0.4 // <-- Number
}]
CodePudding user response:
Very easy
const array = [{
label: 'foo',
page: 1,
rank: '1',
decimal: '0.1'
},{
label: 'foo',
page: 1,
rank: '2',
decimal: '0.4'
}]
const returnValue = val => !isNaN(parseFloat(val)) ? parseFloat(val) : val
const a2 = array.map(
obj => Object.fromEntries(
Object.entries(obj).map(
([key, value]) => [key, returnValue(value)]
)
)
)
console.log(a2)
CodePudding user response:
To update the same Array, just use Array.forEach
, if you want to create a new Array, use Array.map
approach
Array.forEach
approach
const array = [
{ label: "foo", page: 1, rank: "1", decimal: "0.1" },
{ label: "foo", page: 1, rank: "1", decimal: "0.1" },
];
array.forEach((value) => {
Object.entries(value).forEach(([key, val]) => {
value[key] = !isNaN(parseFloat(val)) ? parseFloat(val) : val;
});
});
console.log(array);
Array.map
approach
const array = [
{ label: "foo", page: 1, rank: "1", decimal: "0.1" },
{ label: "foo", page: 1, rank: "1", decimal: "0.1" },
];
const response = array.map((value) => {
return Object.entries(value).reduce((acc, [key, val]) => {
acc[key] = !isNaN(parseFloat(val)) ? parseFloat(val) : val;
return acc;
}, {});
});
console.log(response);
CodePudding user response:
const array = [{
label: 'foo',
page: 1,
rank: '1',
decimal: '0.1'
},{
label: 'foo',
page: 1,
rank: '1',
decimal: '0.1'
}]
const parsedArray = array.map(element =>
Object.entries(element).reduce((acc, [key,value]) => {
return {
...acc,
[key]: isFinite( value) ? value : value,
}
},{}));
console.log(parsedArray);