1

I am trying to convert an object to an array with pure javascript.

I want to convert this:

[{"itemCode":"Mob-mtr"},{"itemCode":"640-chr"}]

to this:

["Mob-mtr","640-chr","541-mtr"]

i have tried this code:

var arr = Object.keys(obj).map(function (key) {return obj[key]});

and a bunch of other variations with no success.

Any idea how i can convert this object to an array?

user2062455
  • 411
  • 5
  • 14
  • Possible duplicate of [From an array of objects, extract value of a property as array](http://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array) – Rajesh May 15 '16 at 08:44

3 Answers3

2

You can use the property directly for the return value.

var array = [{ "itemCode": "Mob-mtr" }, { "itemCode": "640-chr" }],
    result = array.map(function (a) { return a.itemCode; });

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0
var data = [{"itemCode":"Mob-mtr"},{"itemCode":"640-chr"}];
var arr=[];
//get all objects in data.
data.forEach(function(obj){
  //get all properties of the object.
  Object.keys(obj).forEach(function(prop){
     arr.push(obj[prop]);
  });
});

console.log(arr);

The chosen answer is perfect, but maybe this will help when these properties are not same or unpredictable, who knows.

sfy
  • 2,810
  • 1
  • 20
  • 22
0

var oldArray = [
  {"itemCode": "Mob-mtr"},
  {"itemCode": "640-chr"},
  {"itemCode": "541-mtr"}
];

var newArray = [];

oldArray.forEach(function(v) {
  newArray.push(v['itemCode']);
});

document.write(newArray);
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95