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

前端 未结 5 705
不知归路
不知归路 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:24

    Something like

    service.getData(function(data) {
        var map = {};
        var varNamePrefix = 'data';
        map = $.map(data, function(item, i) {
            return getProperties(item, varNamePrefix);
        });
    });
    
    service.getSomething(function(data) {
        var map = {};
        var varNamePrefix = 'something';
        map = $.map(data, function(item, i) {
            return getProperties(item, varNamePrefix);
        });
    });
    
    function getProperties(item, varNamePrefix) {
        var ret = {};
        ret.key = item[varNamePrefix + '1'];
        ret.value = item[varNamePrefix + '2'];
        return ret;
    }
    

    May help?

    Basically, you could use a function that takes a property prefix and uses it to form the actual property names to get from items.

提交回复
热议问题