sk_225
sk_225

Reputation: 425

JS: Convert a specific values from an object into an array?

I have an object:

var obj = 
[
 {
   "value": "aep",
   "label": "AEP"
 },
 {
   "value": "cap",
   "label": "CAP"
 },
 {
   "value": "casl",
   "label": "CASL"
 } ] 

And I want to convert the values of the labels ONLY into an array so that the end result is:

["AEP", "CAP", "CASL"]

How do I only get the label values converted in an array?

Upvotes: 0

Views: 137

Answers (4)

theblindprophet
theblindprophet

Reputation: 7927

First: obj is not an object, it is an array since the parent brackets are [] and not {}. I will, however, keep the name the same. This might have caused you some confusion, e.g.

var object = {};
var array = [];
var arrayOfObjects = [{},{},{}];
var objectOfArrays = {array1: [],array2: [],array3: []};

To loop an array you can use a for loop:

// new array
var newArray = [];
// iterates over each index in the array
for(var i=0; i<obj.length; i++) {
    // Access the specific index, then access its `label` property
    // Push into `newArray`
    newArray.push(obj[i].label);
}

console.log(newArray);

Codepen: http://codepen.io/theblindprophet/pen/RRxVba

Upvotes: 1

markusthoemmes
markusthoemmes

Reputation: 3120

This is a functional solution and not the most straightforward one, you may want to refer to @theblindprophet's answer for the imperative approach to this problem.

Pretty easy task to be done in a functional way:

var labels = obj.map(function(inner) { return inner.label });

How does one approach such a problem: You need to think of how to transform the data you have to the data you want. In this case you have an Array of Objects and you want to transform this Array of Objects to an Array of Strings placed inside that Object.

The above code iterates over the Array and returns the value you want for the current element of the Array, building a new Array in the course (map)

Upvotes: 0

Jigar Patel
Jigar Patel

Reputation: 1

Its simple. You can use map function of javascript array

var obj = 
[
 {
   "value": "aep",
   "label": "AEP"
 },
 {
   "value": "cap",
   "label": "CAP"
 },
 {
   "value": "casl",
   "label": "CASL"
 } ] 

var arr = obj.map(function(data){return data.value});

Upvotes: 0

Hector Barbossa
Hector Barbossa

Reputation: 5528

Using a for loop

 var out = [];
 for (var i = 0, len = obj.length; i < len; i++) {
     out.push(obj[i].label);
 }
 console.log(out);

Upvotes: 0

Related Questions