-6

I have the following JSON Array

var myObj = [{
  1: ['one'],
  2: ['two'],
  3: ['three']
}];

I want to convert this to an array like below

['one', 'two', 'three'] 
Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
Segun Kess
  • 243
  • 4
  • 7

5 Answers5

1

Keeping in mind that object keys have no guaranteed order, I'd get all the entries, sort them on the index, and them map them to the first index of their values.

var myObj = [{
  1: ['one'],
  2: ['two'],
  3: ['three']
}];

var myArr = Object.entries(myObj[0])
  .sort(([k1, _], [k2, __]) => k1 - k2)
  .map(([_, [v]]) => v);

console.log(myArr);
0

One way of doing it in jquery-

var myObj = [{
  1: ['one'],
  2: ['two'],
  3: ['three']
}];

var res = [];
$.each(myObj[0], function(index, value) {
  res.push(value[0]);
});

console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
Sanchit Patiyal
  • 4,910
  • 1
  • 14
  • 31
0
Object.keys(myObj[0]).map(item => myObj[0][item][0])
zabusa
  • 2,520
  • 21
  • 25
0

While object's keys with stringed integers are sorted by their value, you could take just the values and concat an array.

var array = [{ 3: ['three'], 1: ['one'], 2: ['two'] }],
    result = array.reduce((r, o) => r.concat(...Object.values(o).map(([a]) => a)), []);
    
console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0
var myObj = {
  1: ['one'],
  2: ['two'],
  3: ['three']
};

var array1 = [];
for (var i = 1; i < 4; i++) {

  var j = myObj[i];
  array1.push(j);

}
console.log(array1);

If Your Object parameters are numbered u can do that, if not try to arrange it in to some kind of order so u can loop it

hope it works

Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
bobriloTM
  • 1
  • 2