0

I want to fetch a property list from a json array. below is json array

[ { treeName: 'tree_A', prefix: 'prefix' }, { treeName: 'tree_b', prefix: 'prefix1/' } ]

After running code, my expectation result is ["tree_A","tree_B"];

Below is my implementation:

var treeNames = [];
        for (var index = 0; index < config.treeSources.length; index++) {
            treeNames.push(config.treeSources[index].treeName);
        }

I want to find a best implementation to make code beautiful..

any one want to play it?

Linqtoxml
  • 7
  • 4
  • lodash version:`_.forEach(config.treeSources, function (source) { treeNames1.push(source.treeName); });` – Linqtoxml Apr 16 '15 at 03:05
  • is there any function in javascript like C# lambda `var result = list.select(x=>x.treeNmae).list();`? – Linqtoxml Apr 16 '15 at 03:07
  • *"I want to find a best implementation to make code beautiful'* How do you define "best"? Is the "best" implementation the shortest? The one the uses the least memory? Least CPU? The one that is most compatible with existing runtimes? – Felix Kling Apr 16 '15 at 03:11
  • Actually I want "to make code beautiful". it looks like short and have good a understanding, but your question is useful for me(new boy in javascript). It makes my eyes brightened. – Linqtoxml Apr 16 '15 at 03:19

2 Answers2

2

Check out Lodash/Underscore's _.pluck function. It does exactly what you want:

var treeNames = _.pluck(config.treeSources, 'treeName')

Using an entire utility library like Lodash or Underscore is probably overkill if your only going to use it for this one function, however, although they do provide a wide variety of very useful other functions.

tomb
  • 1,817
  • 4
  • 21
  • 40
  • Please, if this answer solves your question, set it as the accepted answer by clicking the green tick beside the question ;) – tomb Apr 16 '15 at 03:12
  • you can avoid lodash if all you need is pluck: `function pluck(x){ "use strict"; return x[this];}`, then use it anytime with [].map() (or filter): `config.treeSources.map(pluck, 'treeName');` – dandavis Apr 16 '15 at 03:50
0

I'll do it something like bellow using native map

var data = [ { treeName: 'tree_A', prefix: 'prefix' }, { treeName: 'tree_b', prefix: 'prefix1/' } ];
var treeNames = data.map(function (tree) {
    return tree.treeName;
});

console.log(treeNames);

Note:- The IE8 doesn't support map function, so if want this on IE8 you have to use native for loop or some library like underscorejs.

Mritunjay
  • 25,338
  • 7
  • 55
  • 68