如何获取数组中对象的索引并将该值连接到对象键上?
我有这个数组:
var arr = [
{
itemCategory: "cats",
itemSku: "12345",
itemSubTotal: 10,
itemQuantity: 2,
},
{
itemCategory: "dogs",
itemSku: "56789",
itemSubTotal: 5,
itemQuantity: 1,
}
]
并且我需要这种格式:
var arr = [
{
itemCategory1: "cats",
itemSku1: "12345",
itemSubTotal1: 10,
itemQuantity1: 2,
},
{
itemCategory2: "dogs",
itemSku2: "56789",
itemSubTotal2: 5,
itemQuantity2: 1,
}
]
如何获取当前对象的索引号并将其附加到对象的键?我能做的最好的事情就是这样:
var newArr=[];
for (var i = 0; i < arr.length; i++){
var obj = arr[i];
for (var key in obj){
var value = obj[key];
var j = i;
j = j+=1;
newArr.push(key + j + ": " + value);
}
}
但它只给了我一个平面数组:
0: "itemCategory1: cats"
1: "itemSku1: 12345"
2: "itemSubTotal1: 10"
3: "itemQuantity1: 2"
4: "itemCategory2: dogs"
5: "itemSku2: 56789"
6: "itemSubTotal2: 5"
7: "itemQuantity2: 1"
感谢我只是将它推入一个数组,但我不知道如何用这些索引号更新对象键。
感谢您的帮助;非常感谢。
I have this array:
var arr = [
{
itemCategory: "cats",
itemSku: "12345",
itemSubTotal: 10,
itemQuantity: 2,
},
{
itemCategory: "dogs",
itemSku: "56789",
itemSubTotal: 5,
itemQuantity: 1,
}
]
and I need this format:
var arr = [
{
itemCategory1: "cats",
itemSku1: "12345",
itemSubTotal1: 10,
itemQuantity1: 2,
},
{
itemCategory2: "dogs",
itemSku2: "56789",
itemSubTotal2: 5,
itemQuantity2: 1,
}
]
How do I take the index number of the current object and append it to the key of the object? The best I could do is this:
var newArr=[];
for (var i = 0; i < arr.length; i++){
var obj = arr[i];
for (var key in obj){
var value = obj[key];
var j = i;
j = j+=1;
newArr.push(key + j + ": " + value);
}
}
but it only gives me a flat array:
0: "itemCategory1: cats"
1: "itemSku1: 12345"
2: "itemSubTotal1: 10"
3: "itemQuantity1: 2"
4: "itemCategory2: dogs"
5: "itemSku2: 56789"
6: "itemSubTotal2: 5"
7: "itemQuantity2: 1"
Appreciate I'm only pushing it into an array, but I could not figure out how to update the object keys with those index numbers.
Thanks for any help; much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
工作演示:
Working Demo :
在您的代码中,这一行:
应该是这样的:
我认为将键映射到新对象可能会更清晰
In your code, this line:
should be this:
I thought it might be cleaner to map the keys over to a new object