Equivalent of Underscore _.pluck in pure JavaScript

前端 未结 6 1293
旧巷少年郎
旧巷少年郎 2020-12-14 07:05

I\'m trying to recreate the Underscore pluck function using pure JS. However, I keep getting an array of undefineds being returned, instead of the actual values from the pr

6条回答
  •  情深已故
    2020-12-14 07:56

    You are so close. You need to change:

    newArr.push(arr[i].key);
    

    to:

    newArr.push(arr[i][key]);
    

    Consider this:

    var obj = { myKey: 'my Value', theKey: 'another value' };
    var theKey = 'myKey';
    
    alert(obj.theKey); // another value
    alert(obj[theKey]); // my Value
    // You can also send in strings here:
    alert(obj['theKey']); // another value
    

    Hope you get my point.

提交回复
热议问题