简体   繁体   English

为数组中的每个元素添加属性/索引

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

I call a webservice that returns an array of objects:我调用一个返回对象数组的网络服务:

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

This is the response:这是回应:

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

I want add a property row_number to each element which contains the current index of the element in the array.我想为每个元素添加一个属性row_number ,其中包含数组中元素的当前索引。

I need this because I am changing the order of the elements later on but want to be able to identify the original position of an element.我需要这个,因为我稍后会更改元素的顺序,但希望能够识别元素的原始位置。

There is nothing really special to do.没有什么特别的事情要做。 Simply iterate over the array and add the property to each element:只需遍历数组并将属性添加到每个元素:

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;
});

See Access / process (nested) objects, arrays or JSON for more general information about nested data structures in JavaScript.有关 JavaScript 中嵌套数据结构的更多一般信息请参阅访问/处理(嵌套)对象、数组或 JSON

You could also use map in case you want to keep the old object around, or wanted to do it in a call chain not modifying an existing array.如果您想保留旧对象,或者想在不修改现有数组的调用链中执行此操作,您也可以使用 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" }]

If foo is one object you can do如果 foo 是你可以做的一个对象

foo.Row_Number

if is list you can use $.each and do the same for each object.如果是列表,您可以使用 $.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