Convert array of objects into array list (javascript)

Question!

I have an array of objects as shown here.

states: Array[3]
[0-2]
 0:Object
     Value: "34343"
 1:Object
     Value: "2332"
 2:Object
     Value: "2333"

I want to convert the above array of objects into the array list as shown below. Can someone please let me know how to achieve something like this in javascript.

states: ["34343", "2332", "2333"]


Answers

The nicest way to do this is as suggested in the comments:

(where var arr is your array)

new_arr = arr.map(el => el.Value)

This is a neat solution that makes use of latest es6 features array.prototype.map and the arrow function.

If you are not using es6 in your project you may be stuck with plain old es5 - perhaps you have underscore or lodash though? In that case:

new_arr = _.map(arr, function(el) {
  return el.Value;
});

Failing this if you do not have underscore and no es6 you may have to resort to using a loop to do it yourself the 'old' way:

new_arr = []
for (var i = 0, j = arr.length; i < j; i++) {
  new_arr.push(arr[i].Value);
}


var inputArray = [{
  value: 1
}, {
  value: 2
}];

var normalizedArray = inputArray.map(function(obj) {
  return obj.value;
});

console.log(normalizedArray.join(","))

You can use Array.map

By : Sreekanth


or in ES6

var stateObject = [{value : 123}, {value : 654}, {value : 654}];
var stateArray = stateObject.map(item => item.value);
console.log(stateArray); // [ 123, 654, 654 ]


This video can help you solving your question :)
By: admin