【发布时间】:2021-05-12 00:57:55
【问题描述】:
我有一个如下所示的对象数组:
const products = [{
"listPrice": 50,
"discount": 10,
"total": 45,
"users": "",
"userNumber": 10,
"userlistPrice": 120,
"userDiscount": 10,
"userTotal": 108
},
{
"listPrice": 1000,
"discount": 10,
"total": 900,
"userNumber": 100,
"userlistPrice": 1200,
"userDiscount": 0,
"userTotal": 1200
},
{
"listPrice": 100,
"discount": 0,
"total": 100,
"userNumber": "",
"userlistPrice": "",
"userDiscount": 0,
"userTotal": ""
},
{
"listPrice": 100,
"discount": 10,
"total": 90,
"userNumber": 100,
"userlistPrice": 1200,
"userDiscount": 0,
"userTotal": 1200
},
{
"listPrice": 5000,
"discount": 0,
"total": 5000,
"userNumber": "",
"userlistPrice": "",
"userDiscount": 0,
"userTotal": ""
},
{
"name": "",
"listPrice": "",
"discount": 0,
"total": ""
},
{
"name": "",
"listPrice": "",
"discount": 0,
"total": ""
}
]
我需要将所有users 键(userNumber、userListPrice 等)放入一个新对象之后,紧跟在同一个数组中。
首先我尝试使用for loop 进行此操作,然后尝试使用forEach,最后使用filter,但我没有得到任何结果。我也尝试使用splice,但无法正确获取索引。
如果有人能指出我正确的方向,我将不胜感激。
预期结果是这样的:
const products = [{
"listPrice": 50,
"discount": 10,
"total": 45,
},
{
"users": "",
"userNumber": 10,
"userlistPrice": 120,
"userDiscount": 10,
"userTotal": 108
},
{
"listPrice": 1000,
"discount": 10,
"total": 900,
},
{
"userNumber": 100,
"userlistPrice": 1200,
"userDiscount": 0,
"userTotal": 1200
}]
解决这个问题的尝试在这个小提琴中:https://jsfiddle.net/7hkouzpn/
【问题讨论】:
-
“我尝试使用 for 循环,然后尝试使用 forEach ...” 请附上您的尝试,以便我们帮助您理解和解决问题
-
使用
for循环。向我们展示您的尝试 -
这里有一个提示:你可以使用
.map((ele) => return ....) -
预期输出是什么?你能帮我解决这个问题,我可以帮你搞定逻辑吗?
-
这是我试过的小提琴:jsfiddle.net/7hkouzpn
标签: javascript arrays