簡體   English   中英

將數組轉換為自定義格式

[英]Converting array in to custom format

如何將下面的數組轉換為下面指定的另一種格式:

我的數組:

var test=[{"1":"Input"},{"2":"Output"}]

轉換后的數組:

var result=

    [
        {
            "id": "1",
            "name": "Input"
        },
        {
            "id": "2",
            " name": "Output"
        }
    ]

我嘗試使用此代碼,但無法正常工作。

var result = [];
for (var i = 0; i < test.length; i++) {
  var newArray = {
    id: Object.keys(test[i])[i],
    name: test[i].name
  }
  result.push(newArray);
}

內部數組對象沒有name屬性,因此test[i].name將是未定義的。 您需要使用鍵值來獲取值。 您也可以使用map()代替for循環來簡化代碼。

 var test = [{ "1": "Input" }, { "2": "Output" }]; var res = test.map(function(v) { // iterating over array object var k = Object.keys(v)[0]; // getting object keys as an array & retrieving first key return { id: k, // setting id property as key name: v[k] // and name property as value } }); document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>'); 

您應該使用array.prototype.map使用轉換函數將一個數組轉換為另一個數組。

array.prototype.map將在所有項目上進行迭代,並在每個項目上運行“轉換功能”。

由於您的項目是一個如下所示的鍵值: {"1":"Input"} ,因此您唯一的問題是您不知道鍵。

要獲取每個對象的鍵,可以使用Object.keys方法。

var test=[{"1":"Input"},{"2":"Output"}]; // input

var newArr = test.map(function(item){
   var key = Object.keys(item)[0]; // get the object's keys and take the only key.
   return {id: key, name: item[key]} // return the new object
}); 

暫無
暫無

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

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