3 回答
TA贡献1796条经验 获得超4个赞
由于 op 声明属性名称未知。您需要使用键来获取属性,然后检查类型,然后使用键更新值。
const people = [
{name: 'John', age: 23, sex: "male"},
{name: 'Andrew', age: 3, sex: "male"},
{name: 'Peter', age: 8, sex: "male"},
{name: 'Hanna', age: 14, sex: "male"},
{name: 'Adam', age: 37, sex: "male"}];
people.forEach(obj=> {
Object.keys(obj).forEach(key=>{
if (typeof obj[key] === "number") {
obj[key] = "$" + obj[key];
}
});
});
console.log(people);
TA贡献1788条经验 获得超4个赞
您可以数组并有条件地修改对象中属性的值map。people请注意, usingmap将为您提供一个新数组。
const people = [
{name: 'John', age: 23, sex: "male"},
{name: 'Andrew', age: 3, sex: "male"},
{name: 'Peter', age: 8, sex: "male"},
{name: 'Hanna', age: 14, sex: "male"},
{name: 'Adam', age: 37, sex: "male"}];
const result = people.map(obj => {
return Object.fromEntries(Object.entries(obj).map(([k, v]) => {
return (typeof v === 'number') ? [k, `$${v}`] : [k, v];
}));
});
console.log(result)
TA贡献1786条经验 获得超11个赞
res = people.map((elem) => {
for(let key in elem){
if(typeof elem[key] == 'number'){
elem[key] += '$';
}
}
return elem;
})
添加回答
举报