我正在嘗試更改所有可能變成數字但以字串形式出現的值
const array = [{
label: 'foo',
page: 1,
rank: '1',
decimal: '0.1'
},{
label: 'foo',
page: 1,
rank: '2',
decimal: '0.4'
}]
我想將此條件用于所有值:
const returnValue = !isNaN(parseFloat(val)) ? parseFloat(val) : val
但不確定如何在不指定 each 的情況下迭代物件陣列key。
我已經這樣做了,但不確定它的效率如何
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)
期望的輸出
const array = [{
label: 'foo',
page: 1,
rank: 1, // <-- Number
decimal: 0.1 // <-- Number
},{
label: 'foo',
page: 1,
rank: 2, // <-- Number
decimal: 0.4 // <-- Number
}]
uj5u.com熱心網友回復:
很容易
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)
uj5u.com熱心網友回復:
要更新相同的陣列,只需使用Array.forEach,如果要創建新陣列,請使用Array.map方法
Array.forEach方法
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方法
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);
uj5u.com熱心網友回復:
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);
uj5u.com熱心網友回復:
如果您不介意使用lodash庫 ( mapValues ),則可以減少代碼量。
const array = [{label: 'foo',page: 1,rank: '1',decimal: '0.1'},{label: 'foo',page: 1,rank: '2',decimal: '0.4'}];
const result = array.map(obj => _.mapValues(obj, value => Number(value) || value));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/512805.html
