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?

1

3 Answers 3

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>');

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.