簡體   English   中英

為數組中的每個元素添加屬性/索引

[英]Add property/index to each element in an array

我調用一個返回對象數組的網絡服務:

$.ajax({
  dataType: "json",
  url: "WebServices/FetchMenu.aspx?P=0&L=2&mt=1",
  //data: data,
  success: function (data) {
    var foo = data;
  }
});

這是回應:

[
    {
        color: "red",
        value: "#f00"
    },
    {
        color: "green",
        value: "#0f0"
    },
    {
        color: "blue",
        value: "#00f"
    },
    {
        color: "cyan",
        value: "#0ff"
    }
]

我想為每個元素添加一個屬性row_number ,其中包含數組中元素的當前索引。

我需要這個,因為我稍后會更改元素的順序,但希望能夠識別元素的原始位置。

沒有什么特別的事情要做。 只需遍歷數組並將屬性添加到每個元素:

for (var i = 0; i < foo.length; i++) {
  foo[i].row_number = i;
}

// or with forEach

foo.forEach(function(row, index) {
  row.row_number = index;
});

有關 JavaScript 中嵌套數據結構的更多一般信息請參閱訪問/處理(嵌套)對象、數組或 JSON

如果您想保留舊對象,或者想在不修改現有數組的調用鏈中執行此操作,您也可以使用 map。

const oldArray = [{a: 'Andy'}, {b: 'Betty'}, {c: 'Charlie'}];
const newArray = oldArray.map((item, index) => ({index, ...item}));
console.log(newArray);
// Array [Object { index: 0, a: "Andy" }, Object { index: 1, b: "Betty" }, Object { index: 2, c: "Charlie" }]

如果 foo 是你可以做的一個對象

foo.Row_Number

如果是列表,您可以使用 $.each 並對每個對象執行相同操作。

$.each(obj, function (index) {
    this.row_number = index + 1;
});
let index = 0;
items.forEach((item) => (item.index = index++));

暫無
暫無

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

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