【问题标题】:how to create and new object when using map?使用地图时如何创建和新对象?
【发布时间】:2019-03-20 17:37:47
【问题描述】:

我有一个关于跟随的问题,我必须从 list1 创建 list2,所以我应用了效果很好的解决方案 1。但是,我必须将其作为单元测试的单独功能。更改后,我无法使其像解决方案 2 那样。如果我打印返回值,它会显示数组的 3 个元素未定义。有人对这个问题有什么建议吗?我已经很努力了,但我仍然无法解决它。

var list1 = [
  { firstName: 'Sofia', lastName: 'I.', country: 'Argentina', continent: 'Americas', age: 35, language: 'Java' },
  { firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 'Europe', age: 35, language: 'Python' },
  { firstName: 'Madison', lastName: 'U.', country: 'United States', continent: 'Americas', age: 32, language: 'Ruby' } 
];

var list2 = [
  { firstName: 'Sofia', lastName: 'I.', country: 'Argentina', continent: 'Americas', age: 35, language: 'Java',
    greeting: 'Hi Sofia, what do you like the most about Java?'
  },
  { firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 'Europe', age: 35, language: 'Python',
    greeting: 'Hi Lukas, what do you like the most about Python?'
  },
  { firstName: 'Madison', lastName: 'U.', country: 'United States', continent: 'Americas', age: 32, language: 'Ruby',
    greeting: 'Hi Madison, what do you like the most about Ruby?'
  } 
];

解决方案 1

let greetings1 = list1.map(person => {
  return Object.assign(
    { firstName: person.firstName },
    { lastName: person.lastName },
    { country: person.country },
    { continent: person.continent },
    { age: person.age },
    { language: person.language },
    {
      greeting: `Hi ${person.firstName}, what do you like the most about ${
        person.language
      }?`
    }
  );
});

解决方案 2

function greetDevelopers(list1) {
  const greetings = list1.map(person => {
    Object.assign(
      { firstName: person.firstName },
      { lastName: person.lastName },
      { country: person.country },
      { continent: person.continent },
      { age: person.age },
      { language: person.language },
      {
        greeting: `Hi ${person.firstName}, what do you like the most about ${
          person.language
        }?`
      }
    );
  });
  return greetings;
}

【问题讨论】:

  • 解决方案 2 不返回 undefined 中的 map 以外的其他值。只需添加return。顺便说一句,真正的问题是什么?
  • 你为什么用Object.assign而不是写:{firstName: person.firstName, lastName: person.lastName, country: person.country, continent: person.continent /*, ... */ }?您对此有何期待?
  • 如问题所述,我期望 list2。我太傻了,忘记退货了。无论如何,非常感谢。

标签: javascript dictionary functional-programming


【解决方案1】:

这是一个函数式方法:

const input = [{
    firstName: 'Sofia',
    lastName: 'I.',
    country: 'Argentina',
    continent: 'Americas',
    age: 35,
    language: 'Java'
  },
  {
    firstName: 'Lukas',
    lastName: 'X.',
    country: 'Croatia',
    continent: 'Europe',
    age: 35,
    language: 'Python'
  },
  {
    firstName: 'Madison',
    lastName: 'U.',
    country: 'United States',
    continent: 'Americas',
    age: 32,
    language: 'Ruby'
  }
]

// objOf :: String -> Any -> Object
const objOf = prop => x => ({ [prop]: x })

// concatObj :: Object -> Object -> Object
const concatObj = x => y => ({ ...x, ...y })

// pipe :: Array (a -> Any) -> a -> b
const pipe = xs => x => xs.reduce((x, f) => f (x), x)

// greeting :: { firstName::String, language::String } -> String
const greeting = ({
  firstName,
  language
}) => `Hi ${firstName}, what do you like the most about ${language}?`

// appendGreeting :: Object -> Object
const appendGreeting = o => pipe ([ 
  greeting, // (1) Generates the greeting
  objOf ('greeting'), // (2) Creates an object owning greeting property
  concatObj (o) // (3) Concats the input object with the "greeting" one
]) (o)

const output = input.map (appendGreeting)

console.log (output)

【讨论】:

    【解决方案2】:

    我猜你正在处理数据结构和改变它们的函数,这意味着Abstract Data Types,这主要是classes 的同义词。在 javascript 中,有三种主要的方式来处理类或对象:

    你也在做单元测试,你需要清楚的区分应用代码和测试代码。在下面的代码中,为了简单起见,我将使用原型。

    // APPLICATION CODE
    function Person(data) {
      Object.assign(this,data);
      };
      
    Person.prototype.greet = function() {
      return `Hi ${this.firstName}, what do you like the most about ${this.language}`;
    };
    
    // TESTING DATA
    var inputList = [
      { firstName: 'Sofia', lastName: 'I.', country: 'Argentina', continent: 'Americas', age: 35, language: 'Java' },
      { firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 'Europe', age: 35, language: 'Python' },
      { firstName: 'Madison', lastName: 'U.', country: 'United States', continent: 'Americas', age: 32, language: 'Ruby' } 
    ];
    
    // TESTING CODE
    const createAndGreet = (data) => {
      const p = new Person(data);
      data.greeting = p.greet(); 
      return data;
    };
    
    console.log(inputList.map(createAndGreet));

    【讨论】:

      【解决方案3】:

      解决方案 2 不返回 Object.assign,因此返回 undefined。此外,您可以将代码简化为以下内容

      var list1 = [
        { firstName: 'Sofia', lastName: 'I.', country: 'Argentina', continent: 'Americas', age: 35, language: 'Java' },
        { firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 'Europe', age: 35, language: 'Python' },
        { firstName: 'Madison', lastName: 'U.', country: 'United States', continent: 'Americas', age: 32, language: 'Ruby' } 
      ];
      
      function greetDevelopers(list1) {
        return list1.map(o => ({...o, greeting: `Hi ${o.firstName}, what do you like the most about ${o.language}?`}));
      }
      console.log(greetDevelopers(list1));

      【讨论】:

        【解决方案4】:

        您可以通过获取旧属性的副本来获取对象并仅添加新属性。

        let greetings1 = list1.map(person => Object.assign(
            {},
            person,
            { greeting: `Hi ${person.firstName}, what do you like the most about ${person.language}?`}
        ));
        

        解决方案 2 不返回 undefied 以外的其他值,因为您不返回创建的对象。

        function greetDevelopers(list1) {
            const greetings = list1.map(person => {
                return Object.assign(
                //^^^^
                    // ...
                );
           });
           return greetings;
        }
        

        【讨论】:

        • 啊,这可能是一个很好的解决方案,它使代码更简单,非常感谢...
        【解决方案5】:
        function greetDevelopers(list1) {
          const greetings = list1.map(person => {
            return Object.assign( // add return before Object.assign
              { firstName: person.firstName },
              { lastName: person.lastName },
              { country: person.country },
              { continent: person.continent },
              { age: person.age },
              { language: person.language },
              {
                greeting: `Hi ${person.firstName}, what do you like the most about ${
                  person.language
                }?`
              }
            );
          });
          return greetings;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多