簡體   English   中英

將Javascript對象數組轉換為單個簡單數組

[英]Convert Array of Javascript Objects to single simple array

我還無法弄清楚如何正確地做到這一點。

我有一個對象的JS數組,看起來像這樣:

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

我想將其轉換為簡單的單個JS數組,而無需任何鍵,它應如下所示:

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

這些ID可以完全刪除。 任何幫助將非常感激。

只需迭代原始數組,選擇有趣的鍵,然后將它們累積在另一個數組中,就像這樣

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

您可以使用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"]

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM