2 回答

TA貢獻(xiàn)1891條經(jīng)驗 獲得超3個贊
您可以通過組合Object.entries
(獲取數(shù)組)、map
(映射值)和Object.fromEntries
(再次獲取對象)來實現(xiàn):
const maximums = Object.fromEntries( Object.entries(convertToYards).map(([name, value]) => [name, value * maximumYards]) );
const convertToYards = {
"feet": 3,
"meters": 0.9144,
"yards": 1
};
const maximumYards = 500;
const maximums = Object.fromEntries(
Object.entries(convertToYards).map(([name, value]) => [name, value * maximumYards])
);
console.log(maximums);
或者只是使用一個for-in循環(huán);但是,如果可能有繼承的屬性,您可能需要清除convertToYards它們:
const maximums = {};
for (const name in convertToYards) {
maximums[name] = convertToYards[name] * maximumYards;
}
const convertToYards = {
"feet": 3,
"meters": 0.9144,
"yards": 1
};
const maximumYards = 500;
const maximums = {};
for (const name in convertToYards) {
maximums[name] = convertToYards[name] * maximumYards;
}
console.log(maximums);
中間立場是使用keyswith for-of:
const maximums = {};
for (const name of Object.keys(convertToYards)) {
maximums[name] = convertToYards[name] * maximumYards;
}
const convertToYards = {
"feet": 3,
"meters": 0.9144,
"yards": 1
};
const maximumYards = 500;
const maximums = {};
for (const name of Object.keys(convertToYards)) {
maximums[name] = convertToYards[name] * maximumYards;
}
console.log(maximums);

TA貢獻(xiàn)1804條經(jīng)驗 獲得超2個贊
根據(jù)評論,您可以使用for .. in如下代碼片段中所示的普通舊版本:
const convertToYards = {
feet: 3,
meters: 0.9144,
yards: 1,
};
let maximums = {};
for (let a in convertToYards) {
maximums[a] = convertToYards[a] * maximumYards;
}
console.log(maximums);
添加回答
舉報