admin管理员组文章数量:1192339
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.
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.
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.
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.
Share Improve this question edited Sep 16, 2015 at 14:14 Felix Kling 816k180 gold badges1.1k silver badges1.2k bronze badges asked Sep 16, 2015 at 13:30 AliAli 3,4696 gold badges43 silver badges56 bronze badges 7 | Show 2 more comments4 Answers
Reset to default 12There 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.
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.
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.Row_Number
if is list you can use $.each and do the same for each object.
$.each(obj, function (index) {
this.row_number = index + 1;
});
let index = 0;
items.forEach((item) => (item.index = index++));
本文标签: javascriptAdd propertyindex to each element in an arrayStack Overflow
版权声明:本文标题:javascript - Add propertyindex to each element in an array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738465131a2088259.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
foo
but to all objects infoo
? Or just to the first one? An example would clarify a lot. – Felix Kling Commented Sep 16, 2015 at 13:45