2 回答
TA贡献1891条经验 获得超3个赞
您可以通过组合Object.entries
(获取数组)、map
(映射值)和Object.fromEntries
(再次获取对象)来实现:
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循环;但是,如果可能有继承的属性,您可能需要清除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贡献1804条经验 获得超2个赞
根据评论,您可以使用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);
添加回答
举报