将Javascript对象数组转换为单个简单数组

时间:2015-08-10 14:48:07

标签: javascript arrays

我无法弄清楚如何正确地完成这项工作。

我有一个JS对象数组,如下所示:

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

我想把它转换成一个简单的单个JS数组,没有任何键,它应该是这样的:

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

可以完全删除ID。任何帮助都会非常感激。

3 个答案:

答案 0 :(得分:4)

简单地迭代原始数组,选择有趣的键并将它们累积在另一个数组中,就像这样

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' ]

此处,data是问题中的原始数组。 keys是您希望从对象中提取的键数组。

如果你想纯粹使用函数式编程技术,那么你可以使用Array.prototype.reduceArray.prototype.concatArray.prototype.map,就像这样

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' ]

答案 1 :(得分:0)

您可以使用Object.keys().forEach()方法迭代对象数组,并使用.map()构建过滤后的数组。

  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"]

答案 2 :(得分:0)

如何使用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
    ];
});