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

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

    this can be done using the [] operators instead of the .-notation just like in this fiddle ive created just for you :D:

        var data = [{
            data1: 'foo',
            data2: 'bar',
            something1: 'sparky',
            something2: 'arf arf!'},
        {
            data1: 'My name is',
            data2: 'What?',
            something1: 'my name is',
            something2: 'Who?!'}
        ];
    
        function test(data, prop) {
            var d_length = data.length;
            for (var i = 0; i < d_length; i++) {
                alert(data[i][prop]);
            }
        }
    
        test(data, 'data1');
    

提交回复
热议问题