How to pass an object property as a parameter? (JavaScript)

前端 未结 5 834
不知归路
不知归路 2020-12-24 01:54

I\'m not sure if the title is appropriate for what I am trying to achieve

I am mapping JSON results to an array. Because I need to do this over and over again I woul

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-24 02:33

    use [] with a string to pull out properties from objects dynamically.

    var a = { foo: 123 };
    a.foo    // 123
    a['foo'] // 123
    
    var str = 'foo';
    a[str]   // 123
    

    Which means we can refactor your method like so, just pass in the names of the properties you want to read as strings.

    var getKeyValueMap = function(data, keyPropName, valuePropName) {
      return $.map(data, function(item, i) {
        return {
          key:   item[keyPropName],
          value: item[valuePropName]
        }
      });
    };
    
    service.getData(function(data) {
      return getKeyValueMap(data, 'data1', 'data2');
    });
    
    service.getSomething(function(data) {
      return getKeyValueMap(data, 'something1', 'something2');
    });
    

提交回复
热议问题