-5

Lets say I have a object like

> var products = {a:"b", c:"d", e:"f" ... it goes like this}

i want to put this object in array like this

> var arrList = [[a,b],[c,d],[e,f]]

but i couldnt managed it'll be great if you guys help me thank you already

5 Answers5

1

Just loop and add it to the array

var result = []
for (var key in products) { result.push([key,products[key]]) }
Tuan Anh Tran
  • 6,807
  • 6
  • 37
  • 54
1

One possible approach:

var arrList = Object.keys(products).map(function(key) {
  return [key, products[key]];
});

Note, though, that properties order in objects are not guaranteed in JavaScript.

Community
  • 1
  • 1
raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • Above won't work if you're supporting older browsers (IE8 and lower): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys – DenizEng Feb 16 '16 at 11:51
0

You can proceed like this:

var products = {a:"b", c:"d", e:"f"};

var arrList = [];
for(var key in products) { // iterates over products key (e.g: a,c,e)
   arrList.push([key, products[key]]);
};
Damien Fayol
  • 958
  • 7
  • 17
0

Use for-in loop to iterate through object

for (variable in object) => variable is a property name

Try this:

var products = {
  a: "b",
  c: "d",
  e: "f"
};
var arr = [];
for (i in products) {
  arr.push([i, products[i]]);
}
snippet.log(JSON.stringify(arr));
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Rayon
  • 36,219
  • 4
  • 49
  • 76
0

You can do it as follow

products = {a:"b",c:"d",e:"f"};
arrList = [];
for(i in products){
    arrList.push([i,products[i]]);
}
Divyesh Savaliya
  • 2,692
  • 2
  • 18
  • 37