1

I have not been able to figure out how to properly accomplish this.

I have a JS array of objects that looks like this:

[{"num":"09599","name":"KCC","id":null},{"num":"000027","name":"Johns","id":null}]

I would like to convert this into a simple, single JS array, without any of the keys, it should look like this:

[
  "09599",
  "KCC",
  "000027",
  "Johns" ]

The IDs can be dropped entirely. Any help would be really appreciated.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
WhyEnBe
  • 295
  • 7
  • 22

3 Answers3

4

Simply iterate the original array, pick the interesting keys and accumulate them in another array, like this

var keys = ['num', 'name'],
    result = [];

for (var i = 0; i < data.length; i += 1) {
  // Get the current object to be processed
  var currentObject = data[i];
  for (var j = 0; j < keys.length; j += 1) {
    // Get the current key to be picked from the object
    var currentKey = keys[j];
    // Get the value corresponding to the key from the object and
    // push it to the array
    result.push(currentObject[currentKey]);
  }
}
console.log(result);
// [ '09599', 'KCC', '000027', 'Johns' ]

Here, data is the original array in the question. keys is an array of keys which you like to extract from the objects.


If you want to do this purely with functional programming technique, then you can use Array.prototype.reduce, Array.prototype.concat and Array.prototype.map, like this

var keys = ['num', 'name'];

console.log(data.reduce(function (result, currentObject) {
  return result.concat(keys.map(function (currentKey) {
    return currentObject[currentKey];
  }));
}, []));
// [ '09599', 'KCC', '000027', 'Johns' ]
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

You can use Object.keys() and .forEach() method to iterate through your array of object, and use .map() to build your filtered array.

  var array = [{"num":"09599","name":"KCC","id":null},{"num":"000027","name":"Johns","id":null}];

  var filtered = array.map(function(elm){
    var tmp = [];
    //Loop over keys of object elm
    Object.keys(elm).forEach(function(value){
      //If key not equal to id
      value !== 'id'
      //Push element to temporary array
      ? tmp.push(elm[value])
      //otherwise, do nothing
      : false
    });
    //return our array
    return tmp;

  });

  //Flat our filtered array
  filtered = [].concat.apply([], filtered);

  console.log(filtered);
  //["09599", "KCC", "000027", "Johns"]
Paul Boutes
  • 3,285
  • 2
  • 19
  • 22
0

How about using map :

var data =  [
              {"num":"09599","name":"KCC","id":null} 
              {"num":"000027","name":"Johns","id":null}
            ];

var result = data.map(function(obj) {
   return [
       obj.num,
       obj.name,
       obj.id
    ];
});
zianwar
  • 3,642
  • 3
  • 28
  • 37