【问题标题】:Transform values inside object of object转换对象内部的值
【发布时间】:2022-11-03 02:31:49
【问题描述】:

我想在对象的对象内转换值。像这样的东西:

初始对象:

const studentDetails = {
   'details1': {Name: "John", CountryName: "US", value: 1},
   'details2': {Name: "David", CountryName: "AUS", value: 2},
   'details3': {Name: "Bob", CountryName: "UK", value: 3},
};

变换对象:

{
   'details1': {Name: "John", CountryName: "US", value: 2},
   'details2': {Name: "David", CountryName: "AUS", value: 3},
   'details3': {Name: "Bob", CountryName: "UK", value: 4},
};

我已经做了类似的事情,但无法弄清楚

Object.fromEntries(Object.entries(studentDetails).map(([key,
value]) => [key, some data transformation on value]))

【问题讨论】:

  • 所以你只是在增加价值?
  • 它可以是值键上的任何转换,例如递增、平方、除法等

标签: javascript object transformation


【解决方案1】:

你可以做这样的事情

const studentDetails = {details1: { Name: "John", CountryName: "US", value: 1 }, details2: { Name: "David", CountryName: "AUS", value: 2 }, details3: { Name: "Bob", CountryName: "UK", value: 3 }};

const transformValue = (details, transform) => {
    return Object.entries(details).reduce((acc, [key, detail]) => {
        acc[key] = {
            ...detail,
            value: transform(detail.value)
        }

        return acc;
    }, {});
};

console.log(transformValue(studentDetails, (val) => val + 1)); // Increments value
console.log(transformValue(studentDetails, (val) => val * val)); // Squaring values

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 2017-12-01
    相关资源
    最近更新 更多