-3

I had this data

var list = {
        "data": [
            {
                "value": "58",
                "color": "red"
            },
            {
                "value": "45",
                "color": "blue"
            },
            {
                "value": "63",
                "color": "green"
            },
            {
                "value": "32",
                "color": "yellow"
            },
            {
                "value": "25",
                "color": "orange"
            }
        ]
    }

I want only values for array and color in one array.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335

4 Answers4

2

This will work cross-browser

var values = [];
var colors = [];

for (var i = 0; i < list.data.length; i++) {
    values.push(list.data[i].value);
    colors.push(list.data[i].color);

};
Mritunjay
  • 25,338
  • 7
  • 55
  • 68
  • nice answer but beware of [cross-browser compatibility issues](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Browser_compatibility) (IE8 and below mostly) – pomeh Aug 05 '14 at 09:46
0

The code below should achieve if what i understand from your question is correct.

var colorArray = [];
var valueArray = [];

for(var i in list.data) {
  colorArray.push(list.data[i].color);
  valueArray.push(list.data[i].value);
}
biplav
  • 781
  • 6
  • 13
0

You can use map() method of Array:

var values = list.data.map(function(item) { return item.value; });
var colors = list.data.map(function(item) { return item.color; });
hindmost
  • 7,125
  • 3
  • 27
  • 39
  • nice answer but beware of [cross-browser compatibility issues](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Browser_compatibility) (IE8 and below mostly) and it may be better to loop over the array only once – pomeh Aug 05 '14 at 09:45
  • @pomeh And how you would implement such "once" loop with `map()`? – hindmost Aug 05 '14 at 09:49
  • I would use `forEach` instead of `map` in this case :) But there's still cross-browser compat issues – pomeh Aug 05 '14 at 09:51
0

You can use this code:

 colors = [];
 values = [];
 list.data.forEach(function(val, key){ colors.push(val.color); values.push(val.value); })
Omar Qunsul
  • 46
  • 1
  • 3